繁体   English   中英

正则表达式将字母数字值与特定条件匹配

[英]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)).*$

regex101演示

如果要获取捕获组,只需做些小改动:

^(?=.*(best [0-9]|[0-9] best)).*$

regex101演示

它基本上是在寻找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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM