Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegExp to validate a formula (math expression with matched parentheses)?

Tags:

regex

I have used regExp quit a bit of times but still far from being an expert. This time I want to validate a formula (or math expression) by regExp. The difficult part here is to validate proper starting and ending parentheses with in the formula.
I believe, there would be some sample on the web but I could not find it. Can somebody post a link for such example? or help me by some other means?

like image 515
WSK Avatar asked May 25 '10 17:05

WSK


2 Answers

Languages with matched nested parentheses are not regular languages and can therefore not be recognized by regular expressions. Some implementations of regular expression (for example in the .NET framework) have extensions to deal with this but that is really no fun to work with. So I suggest to use an available parser or implement a simple parser yourself (for the sake of fun).

For the extension in the .NET implementation see the MSDN on balancing groups.

like image 92
Daniel Brückner Avatar answered Oct 12 '22 05:10

Daniel Brückner


If your mathematical expression involves matched nested parenthesis, then it's not a regular grammar but a context-free one and as such, can not be parsed using regex.

like image 3
DVK Avatar answered Oct 12 '22 03:10

DVK