【问题标题】:What is the regex pattern for named capturing groups in .NET?.NET 中命名捕获组的正则表达式模式是什么?
【发布时间】:2012-04-26 07:01:29
【问题描述】:

我正在努力使用一种正则表达式模式,该模式会将文本从字符串中提取到命名组中。

一个(有点武断的)示例将最好地解释我想要实现的目标。

string input =
    "Mary Anne has been to 949 bingo games. The last was on Tue 24/04/2012. She won with the Numbers: 4, 6, 11, 16, 19, 27, 45";

string pattern =
    @"(?<Person>\w+?) has been to (?<NumberOfGames>\d+?) bingo games. The last was on (?<Day>...?) (?<Date>...?). She won with the Numbers: (?<Numbers>...?)";

Regex regex = new Regex(pattern);
var match = regex.Match(input);

string person = match.Groups["Person"].Value;
string noOfGames = match.Groups["NumberOfGames"].Value;
string day = match.Groups["Day"].Value;
string date = match.Groups["Date"].Value;
string numbers = match.Groups["Numbers"].Value;

我似乎无法让正则表达式模式工作,但我认为上面的解释已经足够好了。基本上我需要获取人名、游戏数量等。

任何人都可以解决这个问题并解释他们制定的实际正则表达式模式吗?

【问题讨论】:

    标签: c# .net regex


    【解决方案1】:
     string pattern = @"(?<Person>[\w ]+) has been to (?<NumberOfGames>\d+) bingo games\. The last was on (?<Day>\w+) (?<Date>\d\d/\d\d/\d{4})\. She won with the Numbers: (?<Numbers>.*?)$";
    

    其他帖子提到了如何提取组,但是这个正则表达式与您的输入相匹配。

    【讨论】:

      【解决方案2】:

      看看the documentation for Result():

      返回指定替换模式的扩展。

      您不想要任何替换模式,因此这种方法不是正确的解决方案。

      你想访问比赛的组,所以这样做:有a Groups property

      这样您的代码将如下所示:

      string title = match.Groups["Person"].Value;
      string drawNumber = match.Groups["NumberOfGames"].Value;
      

      另外,正如 russau 正确指出的那样,您的模式与您的文本不匹配:Date 不仅仅是三个字符。

      【讨论】:

      • 谢谢,我在这里用你的建议更新了这个问题,但是我想要的是正则表达式模式。
      【解决方案3】:

      试试这个:

      string pattern = @"(?<Person>\w+?) has been to (?<NumberOfGames>\d+?) bingo games. The last was on (?<Day>...?) (?<Date>\d+/\d+/\d+). She won with the Numbers: (?<Numbers>...?)";
      

      您的正则表达式与字符串的日期部分不匹配。

      【讨论】:

        【解决方案4】:

        假设正则表达式有效,获取命名组的代码如下:

        string title = match.Groups["Person"].Value;
        string drawNumber = match.Groups["NumberOfGames"].Value;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-04-16
          • 2019-03-17
          • 2011-03-03
          • 2011-03-31
          相关资源
          最近更新 更多