2010-10-13 54 views
0

我是.NET新手,很難理解Regex對象。在.NET中使用命名組正則表達式

我想要做的是以下。這是僞代碼;我不知道使這項工作的實際代碼如下:

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, 
    }; 
} 

我需要更改以使此代碼有效嗎?

回答

0

A Regex實例在我的機器上沒有Apply方法。我通常會做更像這樣的事情:

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 
    }; 
} 
1

Regex上沒有Apply方法。看起來像你可能正在使用一些未顯示的自定義擴展方法。您還沒有顯示您正在使用的模式。除此之外,可以從Match中檢索組,而不是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;