22

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

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

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;

我似乎无法让正则表达式模式工作,但我认为上面解释得很好。基本上我需要得到人名,游戏数量等。

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

4

4 回答 4

28
 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>.*?)$";

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

于 2012-04-26T07:13:48.383 回答
4

查看以下文档Result()

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

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

你想访问匹配的组,所以这样做:有一个Groupsproperty

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

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

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

于 2012-04-26T07:08:37.683 回答
2

试试这个:

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>...?)";

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

于 2012-04-26T07:08:51.223 回答
1

假设正则表达式有效,获取命名组的代码将是这样的:

string title = match.Groups["Person"].Value;
string drawNumber = match.Groups["NumberOfGames"].Value;
于 2012-04-26T07:05:57.790 回答