Regular expression for arithmetic expression

自闭症网瘾萝莉.ら 提交于 2019-12-24 03:34:56

问题


I,m trying to write a regex to check if the given string is like a + b, 2 + a + b, 3 + 6 * 9 + 6 * 5 + a * b, etc...

Only + and * operators.

I tried

if (str.matches("(\\d|\\w \\+|\\*){1,} \\d|\\w"))

Unfortunately it only handles cases like 3 * 7 ... (numeric * numeric).

Waiting for your answers, thanks for reading me.


回答1:


Put * and + inside a character class.

str.matches("\\w(?:\\s[+*]\\s\\w)+");

DEMO




回答2:


This will handle cases of simple and chained calculations

[0-9A-Za-a]*( ){0,}([+-/*]( ){0,}[0-9A-Za-a]*( ){0,})*

This would match, for example

  • 1+2
  • 1 + 2
  • 1 + a * 14 / 9

(You can change the operators you want by updating [+-/*])



来源:https://stackoverflow.com/questions/29845218/regular-expression-for-arithmetic-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!