Regex match multiple groups

前端 未结 2 1778
灰色年华
灰色年华 2021-01-13 02:02

I have the following example of a string with regex which I am trying to match:

Regex: ^\\d{3}( [0-9a-fA-F]{2}){3}

String to match: 010 00

相关标签:
2条回答
  • 2021-01-13 02:36

    This should work for your current string. I'd need a better example (more strings etc.) to see if this would break for those. The word boundary (\b) checks for any non-word character:

    \b[0-9a-fA-F]{2}\b
    
    0 讨论(0)
  • 2021-01-13 03:01

    Because you have a quantifier on a capture group, you're only seeing the capture from the last iteration. Luckily for you though, .NET (unlike other implementations) provides a mechanism for retrieving captures from all iterations, via the CaptureCollection class. From the linked documentation:

    If a quantifier is applied to a capturing group, the CaptureCollection includes one Capture object for each captured substring, and the Group object provides information only about the last captured substring.

    And the example provided from the linked documentation:

      // 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);
      }
    
    0 讨论(0)
提交回复
热议问题