tags:

views:

31

answers:

2

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?

A: 

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
    };
}
spender
+1  A: 

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("[email protected]");
String user = match.Groups["user"].Value;
String domain = match.Groups["domain"].Value;
Josh Einstein