[英]Regex Match Alphanumeric values with specific conditions
I need to match a string under the following conditions using Regex in C#: 我需要在C#中使用Regex在以下条件下匹配字符串:
Entire string can only be alphanumeric (including spaces). 整个字符串只能是字母数字(包括空格)。 Example string should only match are: ( numerical values can change)
字符串示例仅应匹配:(数值可以更改)
Example1 String: best 5 products Example1字符串:最好的5个产品
Example2 String: 5 best products Example2字符串:5种最佳产品
Example3 String: products 5 best Example3字符串:产品5最好
I am looking to get get "5 best" or "best 5" but the following strings are also matching: 我希望获得“ 5个最佳”或“ 5个最佳”,但以下字符串也匹配:
Example1 String: best anything 5 products Example1字符串:最好的5种产品
Example2 String: 5 anything best products Example2字符串:5种最佳产品
Example3 String: products 5 anything best Example3字符串:产品5最好的
I am using: 我在用:
string utter11 = Console.ReadLine();
string pattern11 = "^(?=.*best)(?=.*[0-9]).*$";
bool match = Regex.IsMatch(utter11, pattern11, RegexOptions.IgnoreCase);
Console.WriteLine(match);
Any suggestions are welcome. 欢迎任何建议。 Thanks
谢谢
You might try this which I made as close as possible to your regex: 您可以尝试一下,使我尽可能接近您的正则表达式:
^(?=.*(?:best [0-9]|[0-9] best)).*$
If you want to get capture groups, just make a minor change: 如果要获取捕获组,只需做些小改动:
^(?=.*(best [0-9]|[0-9] best)).*$
It's basically looking for best [0-9]
or [0-9] best
, which I understood is what you're looking for. 它基本上是在寻找
best [0-9]
或[0-9] best
,据我了解,这就是您要寻找的。
Try (?:(?<=best)\\s+([0-9]))|(?:([0-9])\\s+(?=best))
尝试
(?:(?<=best)\\s+([0-9]))|(?:([0-9])\\s+(?=best))
Expects either a prefix of "best" and then whitespace and a number, or a number and whitespace and then a suffix of "best" 期望前缀为“ best”,然后为空格和一个数字,或者为数字和空格,后缀为“ best”
How about this (complete example): 怎么样(完整示例):
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();
}
}
If you have more examples of what string the pattern should and shouldn't match, I'll refine the expression if necessary. 如果您有更多示例说明模式应该和不应该匹配的字符串,那么如有必要,我将优化表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.