-4

我有一个字符串:

将1放入锅中放入2放入锅中放入3放入锅中...

取决于

把n放进锅里

如何使用 C# 正则表达式获取所有 put 语句,例如:

“将 1 放入锅中”
“将 2 放入锅中”
“将 3 放入锅中”
...
“将 n 放入锅中”

声明n

谢谢

4

2 回答 2

3

我可能不应该回答这个问题,因为您的问题根本没有任何努力,但我认为可能的正则表达式是:

string regex = @"put (?<number>\d+) in pot";

然后你可以使用匹配:

var matches = Regex.Matches("Put 1 in pot put 2 in pot", @"put (?<number>\d+) in pot", RegexOptions.IgnoreCase);
foreach (Match match in matches)
{
    Console.WriteLine(match.Value);
}

要找到实际数字,您可以使用

int matchNumber = Convert.ToInt32(match.Groups["number"].Value);
于 2012-12-10T15:32:11.070 回答
1

你也可以这样做

 var reg=@"put.*?(?=put|$)";
 List<string> puts=Regex.Matches(inp,reg,RegexOptions.Singleline)
                        .Cast<Match>()
                        .Select(x=>x.Value)
                        .ToList();     

put.*?(?=put|$)
------ -------
|         |
|         |->checks if `.*?`(0 to many characters) is followed by `put` or `end` of the file
|->matches put followed by 0 to many characters
于 2012-12-10T15:40:32.017 回答