我是 Regex 的新手,我无法匹配这种句子:Band Name @Venue 30 450
,其中最后的数字代表价格和数量。
string input = "Band Name @City 25 3500";
Match m = Regex.Match(input, @"^[A-Za-z]+\s+[A-Za-z]+\s+[\d+]+\s+[\d+]$");
if (m.Success)
{
Console.WriteLine("Success!");
}
最佳答案
您可以使用 Regex
并利用命名组的使用。如果您需要,这将使以后更容易提取数据。例子是:
string pattern = @"(Band) (?<Band>[A-Za-z ]+) (?<City>@[A-Za-z ]+) (?<Price>\d+) (?<Quantity>\d+)";
string input = "Band Name @City 25 3500";
Match match = Regex.Match(input, pattern);
Console.WriteLine(match.Groups["Band"].Value);
Console.WriteLine(match.Groups["City"].Value.TrimStart('@'));
Console.WriteLine(match.Groups["Price"].Value);
Console.WriteLine(match.Groups["Quantity"].Value);
如果您查看模式,则很少有 regex
名为 ?<GroupName>
的组.这只是一个基本示例,也可以对其进行调整以满足您的实际需求。
关于c# - 如何用正则表达式匹配一个特定的句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48839245/