5

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.

MedAl
  • 457
  • 3
  • 19
  • 1
    The character class (ala @AvinashRaj) is clearly better. Purely for educational purposes the problem with your use of the vertical bar is that you didn't group the things before and after. If you wanted `\\+|\\*` then you needed to group them like `(?:\\+|\\*)`. Same with the `\\d|\\w` although that's not so important since \\w includes \\d. – Peter Bowers Apr 24 '15 at 10:40
  • 1
    Matching operators (vs numerical constants / symbolic names) is only the first step of resolving an expression, called tokenizing. The next step is building a parse tree, so that you can properly evaluate parenthesis inside-out, multiplication before addition, etc. Related answer: https://stackoverflow.com/questions/62374663/regexp-to-match-basic-arithmetic-with-letters-and-put-them-in-groups/62379691 Blog on tokenizer & parse tree: https://blog.bitsrc.io/parsing-expressions-in-javascript-4c156f0cbaec – Peter Thoeny Jun 15 '20 at 17:06

2 Answers2

5

Put * and + inside a character class.

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

DEMO

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • 1
    @MedAl since you're new to StackOverflow, i suggest you to read [this](http://stackoverflow.com/help/accepted-answer) – Avinash Raj Apr 24 '15 at 10:42
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 [+-/*])

Steve Chaloner
  • 8,162
  • 1
  • 22
  • 38