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

sar*_*ake 24 c# regex extraction

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

        Regex regex = new Regex(patternString);
        if (regex.IsMatch(stringToMatch))
        {
            return true;
        }
        else
        {
            return false;
        }
Run Code Online (Sandbox Code Playgroud)

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

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

And*_*mar 66

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

(\d\d\d)-(\d\d\d\d\d\d\d)
Run Code Online (Sandbox Code Playgroud)

让我们将这个正则表达式与电话号码相匹配:

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

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

match.Groups[1].Value
Run Code Online (Sandbox Code Playgroud)

和第二个7位数:

match.Groups[2].Value
Run Code Online (Sandbox Code Playgroud)

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

PS2.第一组存储在Group [1]中,而不是像您期望的那样存储在Group [0]中.那是因为Group [0]包含整个匹配的字符串.

  • +1非常彻底!我添加了一件事,你在match.Groups [1]而不是[0]开始的原因是因为[0]包含整个匹配的字符串. (12认同)

cyb*_*nte 17

请改用分组和匹配.

即:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

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

Regex re = new Regex("(?<Part1>\\d+)-(?<Part2>\\d+)");
Run Code Online (Sandbox Code Playgroud)

和这样访问

  String part1 = m.Groups["Part1"].Value;
  String part2 = m.Groups["Part2"].Value;
Run Code Online (Sandbox Code Playgroud)


Luk*_*keH 13

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

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 正确的正则表达式+1 ...顺便说一句,如果你使用IgnoreCase,你可以使用[az]而不是[A-Za-z]. (2认同)