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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With