Reputation: 916
I dealing with regular expressions, this question arose. How to write a regular expression for math expression tests. I mean expression like this:
1+1
(1+1) * 2 / (4+1) + 3
and somthing like that.
I trying somthing like this:
"^(?:\\d+([*+-]|/(?!0)))+\\d+$"
But so does not pass option with brackets. How to make a regular expression that skipped both options that I described above? I need a regular expression to skip numbers, parentheses and fundamentals mathematical operations + - * / and spaces
Upvotes: 0
Views: 87
Reputation: 24802
You could use the following :
^(?:\d+|\(\d+\s*[-+/*]\s*\d+\))(?:\s*[-+/*]\s*(?:\d+|\(\d+\s*[-+/*]\s*\d+\)))*$
(?:\d+|\(\d+\s*[-+/*]\s*\d+\))
is a single number or a bracketed operation. This is matched at least once, then is followed by as many occurences separated by an operator as necessary.
Upvotes: 1