Regex collection groups in C# when using an OR -


if have following code:

regex xp = new regex(@"(\*\*)(.+?)\*\*|(\*)([^\*]+)\*");  string text = @"*hello* **world**";  matchcollection r_matches = xp.matches(text);  foreach (match m in r_matches) {     console.writeline(m.groups[1].tostring());     console.writeline(m.groups[3].tostring()); }  // outputs: // '' // '*' // '**' // '' 

how can run above regular expression , have result of first collection either side of or appear in same place? (ie. .groups[1] returns either ** or _, gather isn't how regexes in c# work achievable? , if how?)

as 1 of commenters said, can use named groups this. .net more flexible of other regex flavors in allows use same name in different parts of regex, no restrictions. regex:

@"(?<delim>\*\*)(?<content>.+?)\*\*|(?<delim>\*)(?<content>[^*]+)\*" 

...you can extract parts interest this:

foreach (match m in r_matches) {     console.writeline("delimiter: {0}\ncontent: {1}",                       m.groups["delim"].value,                       m.groups["content"].value); } 

and that's there it. contrary 1 of other comments, don't have muck groupcollections or capturecollections, or whatever.

be aware particular problem can solved in flavor. it's .net more flexible most.


Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -