Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate mathematical expressions using regular expression?

Tags:

regex

I want to validate mathematical expressions using regular expression. The mathematical expression can be this

  1. It can be blank means nothing is entered

  2. 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

  3. 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.

like image 278
Bibhu Avatar asked Jun 13 '12 06:06

Bibhu


People also ask

How do you validate a regular expression?

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.

Is regex good for validation?

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.

What is regular expression in maths?

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.

Does Google support regular expressions?

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.


2 Answers

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.

like image 95
Nirvana Avatar answered Oct 11 '22 03:10

Nirvana


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
like image 23
kapa Avatar answered Oct 11 '22 04:10

kapa