Answer the question
In order to leave comments, you need to log in
Isolation of lexemes in mat. expression (using regexps)?
There is a simple mat language. expressions. It contains operations (+-*/, etc., possibly for two or more characters), variables, numbers (integer, fractional).
The task is to split the input expression (for example, “2 + x1 - 12.5 / ((0.24^y) * coeff)”) into lexemes (tokens) (it would also be nice to check the validity).
The task is classical, in the general case it is solved by writing a lexical analyzer (and validation by writing a parser ). Based on Regex pov, I'm currently solving it like this:
<font color="black"><font color="#0000ff">public</font> <font color="#0000ff">static</font> <font color="#2B91AF">IEnumerable</font><<font color="#0000ff">string</font>> TokenizeInfix(<font color="#0000ff">string</font> infix)<br/> {<br/> infix = Regex.Replace(infix, <font color="#A31515">@"[ \t]+"</font>, <font color="#0000ff">string</font>.Empty);<br/> <br/> <font color="#0000ff">var</font> match = Regex.Match(infix, <font color="#A31515">@"[-+*/^%()]|[A-Za-z][A-Za-z0-9]*|[+-]?[0-9]+\.?[0-9]*"</font>);<br/> <br/> <font color="#0000ff">if</font> (match.Success)<br/> <font color="#0000ff">do</font> <font color="#0000ff">yield</font> <font color="#0000ff">return</font> match.Value;<br/> <font color="#0000ff">while</font> ((match = match.NextMatch()).Success);<br/> }</font><br/> <br/> <font color="gray">* This source code was highlighted with <a href="http://virtser.net/blog/post/source-code-highlighter.aspx"><font color="gray">Source Code Highlighter</font></a>.</font>
Answer the question
In order to leave comments, you need to log in
However, in this case, the user has the option to enter "x 1", and this will be treated as a single "x1":variable token. Is it possible to take into account all the conditions in one regexp, so as not to pre-delete whitespace characters?By pre-deleting spaces, you do not simplify the task of parsing the expression, but on the contrary, you complicate it.
var match = Regex.Match(infix, @"[-+*/^%()]|[A-Za-z][A-Za-z0-9]*|[+-]?[0-9]+\.?[0-9]*|[ \t]+");
What is the best way to check the validity of an expression?The task of checking the correctness of an arithmetic expression by means of only regexps, as far as I know, cannot be solved.
...
is it possible to get around only regular expressions, or is it better to use a generator like Coco / R
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question