regex - Parsing mathematical expressions in C# -
as project, want write parser mathematical expressions in c#. know there libraries this, want create own learn topic.
as example, have expression
min(3,4) + 2 - abs(-4.6)
i create token string specifying regular expressions , going through expression user trying match 1 of regex. done front back:
private static list<string> tokenize(string expression) { list<string> result = new list<string>(); list<string> tokens = new list<string>(); tokens.add("^\\(");// matches opening bracket tokens.add("^([\\d.\\d]+)"); // matches floating point numbers tokens.add("^[&|<=>!]+"); // matches operators , other special characters tokens.add("^[\\w]+"); // matches words , integers tokens.add("^[,]"); // matches , tokens.add("^[\\)]"); // matches closing bracket while (0 != expression.length) { bool foundmatch = false; foreach (string token in tokens) { match match = regex.match(expression, token); if (false == match.success) { continue; } result.add(match.value); expression = regex.replace(expression, token, ""); foundmatch = true; break; } if (false == foundmatch) { break; } } return result; }
this works quite well. want user able enter strings expression. found question @ regex tokenize issue answer provide regex match text anywhere in expression. need match first occurrence @ front of expression can keep order of token. example see this:
5 + " smaller " + 10
should give me tokens 5
+
" greater "
+
10
if possible able enter escape characters user able use character " in strings, "this apostrophe \" "
gives me token "this apostrophe " "
the answer wiktor stribiżew @ question looked good, couldn't modify matches @ beginning , 1 word. appreciated!
funny referencing question. adopted (yet again) my answer in there work here ;)
here's fiddle showing solution.
the regex
(?!\+)(?:"((?:\\"|[^"])*)"?)
i changed code use capture groups able in simple manner not add surrounding quotes. loop removes +
sign separating tokens.
regards
Comments
Post a Comment