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.

2
  • 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. Commented Apr 24, 2015 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: stackoverflow.com/questions/62374663/… Blog on tokenizer & parse tree: blog.bitsrc.io/parsing-expressions-in-javascript-4c156f0cbaec Commented Jun 15, 2020 at 17:06

2 Answers 2

5

Put * and + inside a character class.

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

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

@MedAl since you're new to StackOverflow, i suggest you to read this
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 [+-/*])

4 Comments

Why all the {0,} instead of just *?
Since you have * instead of + after the [0-9a-z] your re will also match + or + - * / or etc
It's ( ){0,} so it allows for optional spaces - and only spaces - between the operands
Yes, but space-star ( ` *` ) does the same thing as open-paren-space-close-paren-open-curly-zero-comma-close-curly. \s* would be even better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.