簡體   English   中英

在.NET Regex中使用命名組

[英]Using named groups in .NET Regex

我是.NET的新手,很難理解Regex對象。

我想做的是下面。 它是偽代碼; 我不知道使此工作的實際代碼:

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

為了使此代碼正常工作,我需要更改什么?

正則表達式上沒有Apply方法。 似乎您正在使用一些未顯示的自定義擴展方法。 您還沒有顯示正在使用的模式。 除此之外,可以從Match(而不是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;

我的計算機上的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
    };
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM