Regular expressions C# - is it possible to extract matches while matching?

前端 未结 4 1863
-上瘾入骨i
-上瘾入骨i 2020-12-03 04:31

Say, I have a string that I need to verify the correct format of; e.g. RR1234566-001 (2 letters, 7 digits, dash, 1 or more digits). I use something like:

<
相关标签:
4条回答
  • 2020-12-03 05:24
    string text = "RR1234566-001";
    string regex = @"^([A-Z a-z]{2})(\d{7})(\-)(\d+)";
    Match mtch = Regex.Matches(text,regex);
    if (mtch.Success)
    {
        Console.WriteLine(m.Groups[1].Value);    
        Console.WriteLine(m.Groups[2].Value);    
        Console.WriteLine(m.Groups[3].Value);    
        Console.WriteLine(m.Groups[4].Value);    
        return true;
    }
    else
    {
        return false;
    }
    
    0 讨论(0)
  • 2020-12-03 05:27

    You can use parentheses to capture groups of characters:

    string test = "RR1234566-001";
    
    // capture 2 letters, then 7 digits, then a hyphen, then 1 or more digits
    string rx = @"^([A-Za-z]{2})(\d{7})(\-)(\d+)$";
    
    Match m = Regex.Match(test, rx, RegexOptions.IgnoreCase);
    
    if (m.Success)
    {
        Console.WriteLine(m.Groups[1].Value);    // RR
        Console.WriteLine(m.Groups[2].Value);    // 1234566
        Console.WriteLine(m.Groups[3].Value);    // -
        Console.WriteLine(m.Groups[4].Value);    // 001
        return true;
    }
    else
    {
        return false;
    }
    
    0 讨论(0)
  • 2020-12-03 05:32

    Use grouping and Matches instead.

    I.e.:

    // NOTE: pseudocode.
    Regex re = new Regex("(\\d+)-(\\d+)");
    Match m = re.Match(stringToMatch))
    
    if (m.Success) {
      String part1 = m.Groups[1].Value;
      String part2 = m.Groups[2].Value;
      return true;
    } 
    else {
      return false;
    }
    

    You can also name the matches, like this:

    Regex re = new Regex("(?<Part1>\\d+)-(?<Part2>\\d+)");
    

    and access like this

      String part1 = m.Groups["Part1"].Value;
      String part2 = m.Groups["Part2"].Value;
    
    0 讨论(0)
  • 2020-12-03 05:36

    You can use regex groups to accomplish that. For example, this regex:

    (\d\d\d)-(\d\d\d\d\d\d\d)
    

    Let's match a telephone number with this regex:

    var regex = new Regex(@"(\d\d\d)-(\d\d\d\d\d\d\d)");
    var match = regex.Match("123-4567890");
    if (match.Success)
        ....
    

    If it matches, you will find the first three digits in:

    match.Groups[1].Value
    

    And the second 7 digits in:

    match.Groups[2].Value
    

    P.S. In C#, you can use a @"" style string to avoid escaping backslashes. For example, @"\hi\" equals "\\hi\\". Useful for regular expressions and paths.

    P.S.2. The first group is stored in Group[1], not Group[0] as you would expect. That's because Group[0] contains the entire matched string.

    0 讨论(0)
提交回复
热议问题