Reputation: 475
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.
Upvotes: 5
Views: 8274
Reputation: 8202
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
(You can change the operators you want by updating [+-/*]
)
Upvotes: 2
Reputation: 174706
Put *
and +
inside a character class.
str.matches("\\w(?:\\s[+*]\\s\\w)+");
Upvotes: 5