簡體   English   中英

Regex.Match 和非捕獲組

[英]Regex.Match and noncapturing groups

誰能解釋為什么 Regex.Match 捕獲非捕獲組。 在 MSDN 中找不到任何關於它的信息。 為什么

Regex regexObj = new Regex("(?:a)");
Match matchResults = regexObj.Match("aa");
while (matchResults.Success)
{
    foreach (Capture g in matchResults.Captures)
    {
        Console.WriteLine(g.Value);
    }
    matchResults = matchResults.NextMatch();
}

生產 output

a
a

而不是空的?

捕獲不同於組。

matchResults.Groups[0]

總是整場比賽。 所以你的小組本來是

matchResults.Groups[1],

如果正則表達式是"(a)" 現在因為它是"(?:a)" ,你可以檢查它是否為空。

捕獲是一個單獨的東西——它們允許你做這樣的事情:

如果您有正則表達式"(.)+" ,那么它將匹配字符串"abc"

Group[1] 將是“c”,因為那是最后一個組,而

  1. Groups[1].Captures[0] 是“a”
  2. Groups[1].Captures[1] 是“b”
  3. Groups[1].Captures[2] 是“c”。

暫無
暫無

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

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