I want to validate mathematical expressions using regular expression. The mathematical expression can be this
It can be blank means nothing is entered
If specified it will always start with an operator +
or -
or *
or /
and will always be followed by a number that can have
any number of digits and the number can be decimal(contains .
in between the numbers) or integer(no '.' symbol within the number).
examples : *0.9
, +22.36
, - 90
, / 0.36365
It can be then followed by what is mentioned in point 2 (above line).
examples : *0.9+5
, +22.36*4/56.33
, -90+87.25/22
, /0.36365/4+2.33
Please help me out.
To validate a RegExp just run it against null (no need to know the data you want to test against upfront). If it returns explicit false ( === false ), it's broken. Otherwise it's valid though it need not match anything.
Regular expressions usually let you build a pretty solid input validation that's fairly readable in a very short space of time. Something that does the right job, is maintainable and lets you get onto other things is good in my books. As always, apply common sense and if a regex is a bad tool for the job, don't use it.
Regular expressions are a generalized way to match patterns with sequences of characters. They define a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. “find and replace” like operations.
Google wrote, “If you choose the Custom (regex) filter, you can filter by a regular expression (a wildcard match) for the selected item. You can use regular expression, or regex, filters for page URLs and user queries. The RE2 syntax is used.” Regular expressions.
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 timesIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With