简体   繁体   English

算术表达式的正则表达式

[英]Regular expression for arithmetic expression

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... 我正在尝试编写一个正则表达式来检查给定的字符串是否像a + b,2 + a + b,3 + 6 * 9 + 6 * 5 + a * b等...

Only + and * operators. 仅+和*运算符。

I tried 我试过了

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

Unfortunately it only handles cases like 3 * 7 ... (numeric * numeric). 不幸的是,它仅处理3 * 7 ...(数字*数字)之类的情况。

Waiting for your answers, thanks for reading me. 等待您的答案,感谢您的阅读。

Put * and + inside a character class. *+放在字符类中。

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

DEMO DEMO

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 + 2 1 + 2
  • 1 + a * 14 / 9 1 +一个* 14/9

(You can change the operators you want by updating [+-/*] ) (您可以通过更新[+-/*]来更改所需的运算符)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM