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?
views:
240answers:
2
+3
A:
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.
DVK
2010-05-25 17:55:51
+1 as you took the words out of my mouth. Although one could get close with backtracking but that is limited and it is, quite frankly, a hack and a sign you're using the wrong tool for the job.
Daniel Papasian
2010-05-25 18:17:52
Better worded: *can not be parsed using regex implementations not supporting recursive matching* (Perl, PHP and .NET *can* do this).
Bart Kiers
2010-05-25 18:18:02
@Bart - he didn't specify the language so I guess it is a standard regex, not Perl's
DVK
2010-05-25 18:19:06
@DVK, sure, but as I said: it's not just Perl, but others too. Besides, most regex implementations support look aheads, which cause them to parse/recognize more than regular languages.
Bart Kiers
2010-05-25 18:24:39
+4
A:
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.
Daniel Brückner
2010-05-25 17:58:00
I was to use this RegExp as a pattern in XML schema to validate value of an attribute. Any suggestion in this context?
Leslie Norman
2010-05-25 18:05:51
*but that is really no fun to work with* is an understatement! Trying to dissect such monsters is a nightmare! :)
Bart Kiers
2010-05-25 18:32:34
If you want to use available tools from the XML field you could try using XSLT. XSLT is a Turing-complete language and therefore is capable to do the job but I can not really tell how much effort this would take and if the result would be a nice piece of code.
Daniel Brückner
2010-05-25 19:11:17