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,
Addr开发者_如何转开发ess = 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
};
}
精彩评论