RegEx to split functions

  • Thread starter Thread starter Tim Conner
  • Start date Start date
T

Tim Conner

How can I use regex to split an expression like the
following :

(Round(340/34.12)*2)

into this list :

(
Round
(
340
/
34.12
)
*
2
)

I could not find a sample to this in .Net help.


Thanks in advance,
 
How can I use regex to split an expression like the
following :

(Round(340/34.12)*2)

into this list :

(
Round
(
340
/
34.12
)
*
2
)

Tim,

Regular expressions aren't the best tool for this kind of data
processing (i.e. nested constructs). A recursive-descent parser is a
much better tool (see www.antlr.org for a free one). However,
regexes can do this in .Net.

The following is a modification of some code from page 430 of Jeffrey
Friedl's excellent book "Mastering Regular Expressions, 2nd Edition":

string expression = "(Round(340/34.12)*2)";
string pattern = @"
\(
(?>
(?<TERMS>[^()]+)
|
\( (?<DEPTH>)
|
\) (?<-DEPTH>)
)*
(?(DEPTH)(?!))
\)";

Match m = Regex.Match(expression, pattern,
RegexOptions.IgnorePatternWhitespace);

foreach (Capture c in m.Groups["TERMS"].Captures)
Console.WriteLine(c.ToString());

The result is:

Round
340/34.12
*2


Hope this helps.

Chris.
 
Back
Top