正则表达式C# – 匹配时是否可以提取匹配?

说,我有一个字符串,我需要validation格式的正确; 例如RR1234566-001 (2个字母,7个数字,短划线,1个或更多个数字)。 我使用类似的东西:

  Regex regex = new Regex(patternString); if (regex.IsMatch(stringToMatch)) { return true; } else { return false; } 

这可以告诉我stringToMatch是否遵循patternString定义的patternString 。 我需要的是(我最后提取这些): 123456001 – 即stringToMatch部分。

请注意,这不是关于如何构造正则表达式的问题。 我要问的是:“有没有办法同时匹配和提取值,而不必在以后使用拆分function?”

您可以使用正则表达式组来完成此操作。 例如,这个正则表达式:

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

让我们用这个正则表达式匹配一个电话号码:

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

如果匹配,您将找到前三位数字:

 match.Groups[1].Value 

和第二个7位数:

 match.Groups[2].Value 

PS在C#中,您可以使用@“”样式字符串来避免转义反斜杠。 例如,@“\ hi \”等于“\\ hi \\”。 对正则表达式和路径很有用。

PS2。 第一组存储在Group [1]中,而不是Group [0],如您所料。 那是因为Group [0]包含整个匹配的字符串。

请改用分组和匹配。

即:

 // 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; } 

您也可以为匹配命名,如下所示:

 Regex re = new Regex("(?\\d+)-(?\\d+)"); 

和这样访问

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

您可以使用括号来捕获字符组:

 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; } 
 string text = "RR1234566-001"; string regex = @"^([AZ az]{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; }