[英]How to match a specific sentence with Regex
我是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);
如果查看模式,則幾乎沒有名為?<GroupName>
regex
組。 這只是一個基本的例子,可以調整,以滿足您的實際需求。
這是一個非常古老而精心的方式: 第一種方式
string re1=".*?"; // Here the part before @
string re2="(@)"; // Any Single Character 1
string re3="((?:[a-z][a-z]+))"; // Word 1, here city
string re4="(\\s+)"; // White Space 1
string re5="(\\d+)"; // Integer Number 1, here 25
string re6="(\\s+)"; // White Space 2
string re7="(\\d+)"; // Integer Number 2, here 3500
Regex r = new Regex(re1+re2+re3+re4+re5+re6+re7,RegexOptions.IgnoreCase|RegexOptions.Singleline);
Match m = r.Match(txt);
if (m.Success)
{
String c1=m.Groups[1].ToString();
String word1=m.Groups[2].ToString();
String ws1=m.Groups[3].ToString();
String int1=m.Groups[4].ToString();
String ws2=m.Groups[5].ToString();
String int2=m.Groups[6].ToString();
Console.Write("("+c1.ToString()+")"+"("+word1.ToString()+")"+"("+ws1.ToString()+")"+"("+int1.ToString()+")"+"("+ws2.ToString()+")"+"("+int2.ToString()+")"+"\n");
}
通過上述方式,您可以一次存儲特定值 。 就像你的小組[6]一樣,這種格式有3500或什么價值。
你可以在這里創建自己的正則表達式:正則表達式
簡而言之,其他人給出的答案是正確的。 第二種方式就是創建正則表達式
"([A-Za-z ]+) ([A-Za-z ]+) @([A-Za-z ]+) (\d+) (\d+)"
並匹配任何字符串格式。 你可以創建你贏得正則表達式並在這里測試: Regex Tester
這應該工作:
[A-Za-z ]+ [A-Za-z ]+ @[A-Za-z ]+ \d+ \d+
使用您的代碼,它將是:
string input = "Band Name @City 25 3500";
Match m = Regex.Match(input, "[A-Za-z ]+ [A-Za-z ]+ @[A-Za-z ]+ \d+ \d+");
if (m.Success)
{
Console.WriteLine("Success!");
}
這就是我試圖做的答案:
string input = "Band Name @Location 25 3500";
Match m = Regex.Match(input, @"([A-Za-z ]+) (@[A-Za-z ]+) (\d+) (\d+)");
if (m.Success)
{
Console.WriteLine("Success!");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.