简体   繁体   中英

Using named groups in .NET Regex

I'm new to .NET and having a hard time trying to understand the Regex object.

What I'm trying to do is below. It's pseudo-code; I don't know the actual code that makes this work:

string pattern = ...; // has multiple groups using the Regex syntax <groupName>

if (new Regex(pattern).Apply(inputString).HasMatches)
{
    var matches = new Regex(pattern).Apply(inputString).Matches;

    return new DecomposedUrl()
    {
        Scheme = matches["scheme"].Value,
        Address = matches["address"].Value,
        Port = Int.Parse(matches["address"].Value),
        Path = matches["path"].Value,
    };
}

What do I need to change to make this code work?

There is no Apply method on Regex. Seems like you may be using some custom extension methods that aren't shown. You also haven't shown the pattern you're using. Other than that, groups can be retrieved from a Match, not a MatchCollection.

Regex simpleEmail = new Regex(@"^(?<user>[^@]*)@(?<domain>.*)$");
Match match = simpleEmail.Match("someone@tempuri.org");
String user = match.Groups["user"].Value;
String domain = match.Groups["domain"].Value;

A Regex instance on my machine doesn't have the Apply method. I'd usually do something more like this:

var match=Regex.Match(input,pattern);
if(match.Success)
{
    return new DecomposedUrl()
    {
        Scheme = match.Groups["scheme"].Value,
        Address = match.Groups["address"].Value,
        Port = Int.Parse(match.Groups["address"].Value),
        Path = match.Groups["path"].Value
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM