如何在 C# 中读取正则表达式捕获

时间:2023-03-26
本文介绍了如何在 C# 中读取正则表达式捕获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我开始编写一本 C# 书籍,并决定将 RegEx 加入其中,让枯燥的控制台练习变得更有趣.我想要做的是在控制台中向用户询问他们的电话号码,对照正则表达式进行检查,然后捕获数字,以便我可以按照我想要的方式对其进行格式化.除了 RegEx 捕获部分之外,我已经完成了所有工作.如何将捕获值放入 C# 变量中?

I started a C# book and I decided to throw RegEx's into the mix to make the boring console exercises a little more interesting. What I want to do is ask a user for their phone number in the console, check it against a RegEx, then capture the digits so I can format them the way I want. I've got all that working except the RegEx capture part. How do I get the capture values into C# variables?

还可以随时更正任何代码格式或变量命名问题.

Also feel free to correct any code formatting or variable naming issues.

static void askPhoneNumber()
{
    String pattern = @"[(]?(d{3})[)]?[ -.]?(d{3})[ -.]?(d{4})";

    System.Console.WriteLine("What is your phone number?");
    String phoneNumber = Console.ReadLine();

    while (!Regex.IsMatch(phoneNumber, pattern))
    {
        Console.WriteLine("Bad Input");
        phoneNumber = Console.ReadLine();
    }

    Match match = Regex.Match(phoneNumber, pattern);
    Capture capture = match.Groups.Captures;

    System.Console.WriteLine(capture[1].Value + "-" + capture[2].Value + "-" + capture[3].Value);
}

推荐答案

C# regex API 可能相当混乱.有groupscaptures:

The C# regex API can be quite confusing. There are groups and captures:

  • 一个group代表一个捕获组,用于从文本中提取子串
  • 如果组出现在量词内,则每个组可以有多个捕获.
  • A group represents a capturing group, it's used to extract a substring from the text
  • There can be several captures per group, if the group appears inside a quantifier.

层次结构是:

  • 匹配
    • 集团
      • 拍摄

      (一个匹配可以有多个组,每个组可以有多个捕获)

      (a match can have several groups, and each group can have several captures)

      例如:

      Subject: aabcabbc
      Pattern: ^(?:(a+b+)c)+$
      

      在本例中,只有一组:(a+b+).该组位于量词内,并匹配两次.它生成两个捕获:aababb:

      In this example, there is only one group: (a+b+). This group is inside a quantifier, and is matched twice. It generates two captures: aab and abb:

      aabcabbc
      ^^^ ^^^
      Cap1  Cap2
      

      当组不在量词内时,它只会生成一次捕获.在您的情况下,您有 3 个组,每个组捕获一次.您可以使用 match.Groups[1].Valuematch.Groups[2].Valuematch.Groups[3].Value提取您感兴趣的 3 个子字符串,而完全不诉诸 capture 概念.

      When a group is not inside of a quantifier, it generates only one capture. In your case, you have 3 groups, and each group captures once. You can use match.Groups[1].Value, match.Groups[2].Value and match.Groups[3].Value to extract the 3 substrings you're interested in, without resorting to the capture notion at all.

      这篇关于如何在 C# 中读取正则表达式捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:关闭控制台应用程序的命令? 下一篇:如何中断 Console.ReadLine

相关文章