Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 683
MedAl Avatar asked Mar 16 '23 07:03

MedAl


1 Answers

Put * and + inside a character class.

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

DEMO

like image 165
Avinash Raj Avatar answered Mar 23 '23 10:03

Avinash Raj