我正在努力使用正则表达式模式,将文本从字符串中拉出到命名组中。
一个(有点武断)的例子将最好地解释我正在努力实现的目标。
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;
我似乎无法使正则表达式模式起作用,但我认为上面解释得很好。基本上我需要得到人名,游戏数量等。
任何人都可以解决这个并解释他们制定的实际正则表达式模式吗?
答案 0 :(得分:27)
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>.*?)$";
其他帖子已经提到了如何拉出群组,但此正则表达式与您的输入匹配。
答案 1 :(得分:4)
查看the documentation for Result()
:
返回指定替换模式的扩展。
您不需要任何替换模式,因此此方法不是正确的解决方案。
您想要访问匹配组,请执行以下操作:a Groups
property。
你的代码看起来像这样:
string title = match.Groups["Person"].Value;
string drawNumber = match.Groups["NumberOfGames"].Value;
此外,正如russau正确指出的那样,您的模式与您的文字不符:Date
不仅仅是三个字符。
答案 2 :(得分: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>...?)";
你的正则表达式与字符串的日期部分不匹配。
答案 3 :(得分:1)
假设正则表达式起作用,获取命名组的代码将是:
string title = match.Groups["Person"].Value;
string drawNumber = match.Groups["NumberOfGames"].Value;