简体   繁体   中英

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...

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.

Put * and + inside a character class.

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

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 + a * 14 / 9

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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