[英]Regex Match Alphanumeric values with specific conditions
我需要在C#中使用Regex在以下條件下匹配字符串:
整個字符串只能是字母數字(包括空格)。 字符串示例僅應匹配:(數值可以更改)
Example1字符串:最好的5個產品
Example2字符串:5種最佳產品
Example3字符串:產品5最好
我希望獲得“ 5個最佳”或“ 5個最佳”,但以下字符串也匹配:
Example1字符串:最好的5種產品
Example2字符串:5種最佳產品
Example3字符串:產品5最好的
我在用:
string utter11 = Console.ReadLine();
string pattern11 = "^(?=.*best)(?=.*[0-9]).*$";
bool match = Regex.IsMatch(utter11, pattern11, RegexOptions.IgnoreCase);
Console.WriteLine(match);
歡迎任何建議。 謝謝
您可以嘗試一下,使我盡可能接近您的正則表達式:
^(?=.*(?:best [0-9]|[0-9] best)).*$
如果要獲取捕獲組,只需做些小改動:
^(?=.*(best [0-9]|[0-9] best)).*$
它基本上是在尋找best [0-9]
或[0-9] best
,據我了解,這就是您要尋找的。
嘗試(?:(?<=best)\\s+([0-9]))|(?:([0-9])\\s+(?=best))
期望前綴為“ best”,然后為空格和一個數字,或者為數字和空格,后綴為“ best”
怎么樣(完整示例):
class Program
{
static void Main(string[] args)
{
List<string> validStrings = new List<string>
{
"best 5 products",
"5 best products",
"products 5 best",
"best anything 5 products",
"5 anything best products",
"products 5 anything best",
};
List<string> invalidStrings = new List<string>
{
"best 5 products.",
"5 best product;s",
"produc.ts 5 best",
"best anything 5 product/s",
"5 anything best produc-ts",
"products 5 anything be_st",
};
string pattern1 = @"^(([A-Za-z0-9\s]+\s+)|\s*)[0-9]\s+([A-Za-z0-9\s]+\s+)?best((\s+[A-Za-z0-9\s]+)|\s*)$";
string pattern2 = @"^(([A-Za-z0-9\s]+\s+)|\s*)best\s+([A-Za-z0-9\s]+\s+)?[0-9]((\s+[A-Za-z0-9\s]+)|\s*)$";
string pattern = string.Format("{0}|{1}", pattern1, pattern2);
foreach (var str in validStrings)
{
bool match = Regex.IsMatch(str, pattern);
Console.WriteLine(match);
}
Console.WriteLine();
foreach (var str in invalidStrings)
{
bool match = Regex.IsMatch(str, pattern);
Console.WriteLine(match);
}
Console.Read();
}
}
如果您有更多示例說明模式應該和不應該匹配的字符串,那么如有必要,我將優化表達式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.