Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex capture groups in any order

Tags:

c#

regex

I need to capture attribute values from the string like this:

att_name1=value1|att_name2=value2|att_name3=value3

Attributes can be in any order. Number of attributes is about 50.

I'm aware about lookarounds with which I can match the string. And I wrote the regex that can capture values in particular order:

"^att1=(?<g1>\\w+)\\|att2=(?<g2>\\w+)\\|att3=(?<g3>\\w+)$"

Is it a way to handle any attribute order?

like image 395
optim1st Avatar asked Mar 16 '23 04:03

optim1st


1 Answers

You can use this regex:

\b(\w+)=(\w+)\b

to capture names and values of attributes. Matches will hold your values in Groups[1].Value and Groups[2].Value.

See demo

Sample regex declaration:

var rx = new Regex(@"\b(\w+)=(\w+)\b", RegexOptions.Compiled);

Or better declare it outside the calling method as a private static readonly field.

In case you only want to match known attributes and their respective values, use named capturing groups with alternation operator:

att_name1=(?<att_value1>\w+)|att_name2=(?<att_value2>\w+)|att_name3=(?<att_value3>\w+)

and then access them with .Groups["att_value1"].Value, etc. See a demo here.

like image 62
Wiktor Stribiżew Avatar answered Mar 25 '23 05:03

Wiktor Stribiżew