简体   繁体   English

.NET中命名捕获组的正则表达式模式是什么?

[英]What is the regex pattern for named capturing groups in .NET?

I'm struggling with a regex pattern that will pull out text from a string into named groups. 我正在努力使用正则表达式模式,将文本从字符串中拉出到命名组中。

A (somewhat arbitrary) example will best explain what I'm trying to achieve. 一个(有点武断的)例子将最好地解释我正在努力实现的目标。

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;

I can't seem to get the regex pattern to work, but i think the above explains it well enough. 我似乎无法使正则表达式模式起作用,但我认为上面解释得很好。 Essentially i need to get the person name, the number of games etc. 基本上我需要得到人名,游戏数量等。

Can anyone solve this and explain the actual regex pattern they worked out? 谁能解决这个问题并解释他们制定的实际正则表达式模式?

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

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

Have a look at the documentation for Result() : 看看Result()的文档

Returns the expansion of the specified replacement pattern. 返回指定替换模式的扩展。

You don't want any replacement patterns, so this method is not the right solution. 您不需要任何替换模式,因此此方法不是正确的解决方案。

You want to access groups of the match, so do that: there is a Groups property . 您想要访问匹配的组,所以这样做:有一个Groups属性

With that your code would look like this: 这样你的代码看起来像这样:

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

Also, as russau correctly pointed out, your pattern doesn't match your text: Date is not just three characters. 此外,正如russau正确指出的那样,您的模式与您的文本不匹配: Date不仅仅是三个字符。

Try this: 尝试这个:

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

Your regex isn't matching the date part of the string. 您的正则表达式与字符串的日期部分不匹配。

Assuming the regex works the code for getting the named group would be this: 假设正则表达式工作,获取命名组的代码将是这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM