簡體   English   中英

正則表達式匹配多個組

[英]Regex match multiple groups

我有以下我試圖匹配的帶有正則表達式的字符串示例:

正則表達式: ^\\d{3}( [0-9a-fA-F]{2}){3}

要匹配的字符串: 010 00 00 00

我的問題是 - 正則表達式匹配並捕獲 1 個組 - 字符串末尾的最后一個00 但是,我希望它最終匹配所有三個00組。 為什么這不起作用? 當然括號應該意味着它們都是平等匹配的嗎?

我知道我可以分別輸入三個組,但這只是一個更長的字符串的簡短摘錄,所以會很痛苦。 我希望這會提供一個更優雅的解決方案,但似乎我的理解有所欠缺!

謝謝!

因為您在捕獲組上有一個量詞,所以您只能看到上次迭代的捕獲。 幸運的是,.NET(與其他實現不同)提供了一種通過CaptureCollection 類所有迭代中檢索捕獲的機制。 從鏈接的文檔:

如果將量詞應用於捕獲組,則 CaptureCollection 為每個捕獲的子字符串包括一個 Capture 對象,而 Group 對象僅提供有關最后捕獲的子字符串的信息。

以及鏈接文檔中提供的示例:

  // Match a sentence with a pattern that has a quantifier that  
  // applies to the entire group.
  pattern = @"(\b\w+\W{1,2})+";
  match = Regex.Match(input, pattern);
  Console.WriteLine("Pattern: " + pattern);
  Console.WriteLine("Match: " + match.Value);
  Console.WriteLine("  Match.Captures: {0}", match.Captures.Count);
  for (int ctr = 0; ctr < match.Captures.Count; ctr++)
     Console.WriteLine("    {0}: '{1}'", ctr, match.Captures[ctr].Value);

  Console.WriteLine("  Match.Groups: {0}", match.Groups.Count);
  for (int groupCtr = 0; groupCtr < match.Groups.Count; groupCtr++)
  {
     Console.WriteLine("    Group {0}: '{1}'", groupCtr, match.Groups[groupCtr].Value);
     Console.WriteLine("    Group({0}).Captures: {1}", 
                       groupCtr, match.Groups[groupCtr].Captures.Count);
     for (int captureCtr = 0; captureCtr < match.Groups[groupCtr].Captures.Count; captureCtr++)
        Console.WriteLine("      Capture {0}: '{1}'", captureCtr, match.Groups[groupCtr].Captures[captureCtr].Value);
  }

這應該適用於您當前的字符串。 我需要一個更好的例子(更多的字符串等)來看看這是否會破壞那些。 單詞邊界 (\\b) 檢查任何非單詞字符:

\b[0-9a-fA-F]{2}\b

暫無
暫無

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

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