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

前端 未结 4 1873
-上瘾入骨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: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("(?\\d+)-(?\\d+)");
    

    and access like this

      String part1 = m.Groups["Part1"].Value;
      String part2 = m.Groups["Part2"].Value;
    

提交回复
热议问题