Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Regex: Get sub-capture?

Tags:

c#

regex

I've got a regex...

internal static readonly Regex _parseSelector = new Regex(@"
    (?<tag>" + _namePattern + @")?
    (?:\.(?<class>" + _namePattern + @"))*
    (?:\#(?<id>" + _namePattern + @"))*
    (?<attr>\[\s*
        (?<name>" + _namePattern + @")\s*
        (?:
            (?<op>[|*~$!^%<>]?=|[<>])\s*
            (?<quote>['""]?)
                (?<value>.*?)
            (?<!\\)\k<quote>\s*
        )?
    \])*
    (?::(?<pseudo>" + _namePattern + @"))*
", RegexOptions.IgnorePatternWhitespace);

For which I grab the match object...

var m = _parseSelector.Match("tag.class1.class2#id[attr1=val1][attr2=\"val2\"][attr3]:pseudo");

Now is there a way to do something akin to m.Group["attr"]["name"]? Or somehow get the groups inside the attr group?

like image 317
mpen Avatar asked Mar 03 '26 16:03

mpen


1 Answers

Group names aren't nested in regular expressions - it's a flat structure. You can just use this:

m.Group["name"]
like image 133
Mark Byers Avatar answered Mar 05 '26 06:03

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!