Validate mathematical expressions using regular expression?

You could try generating such a regex using moo and such:

(?:(?:((?:(?:[ \t]+))))|(?:((?:(?:\/\/.*?$))))|(?:((?:(?:(?<![\d.])[0-9]+(?![\d.])))))|(?:((?:(?:[0-9]+\.(?:[0-9]+\b)?|\.[0-9]+))))|(?:((?:(?:(?:\+)))))|(?:((?:(?:(?:\-)))))|(?:((?:(?:(?:\*)))))|(?:((?:(?:(?:\/)))))|(?:((?:(?:(?:%)))))|(?:((?:(?:(?:\()))))|(?:((?:(?:(?:\)))))))

This regex matches any amount of int, float, braces, whitespace, and the operators +-*/%.

However, expressions such as 2+ would still be validated by the regex, so you might want to use a parser instead.


Something like this should work:

^([-+/*]\d+(\.\d+)?)*

Regexr Demo

  • ^ - beginning of the string
  • [-+/*] - one of these operators
  • \d+ - one or more numbers
  • (\.\d+)? - an optional dot followed by one or more numbers
  • ()* - the whole expression repeated zero or more times

Tags:

Regex