【问题标题】:how to restrict wild card for specific search如何限制特定搜索的通配符
【发布时间】:2017-08-03 21:56:16
【问题描述】:

我想验证输入字符串。规则如下:

1) %somestring 2)一些字符串% 3)%somestring%

如果输入的字符串符合上述格式,则为真,否则为假。

注意:somestring 不应该有 %

【问题讨论】:

    标签: c# hql


    【解决方案1】:

    尝试遵循正则表达式。希望我正确地解释了作业。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Text.RegularExpressions;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string[] inputs = {
                   "Where Name like '%A%'",
                   "Where Name like '%A'",
                   "Where Name like 'A%'",
                   "Where Name like '%A%B%C'",
                   "Where Name Like %%",
                   "Where Name Like %"
                                  };
    
                string pattern = @"Where\s+[A-Za-z]+\s+like\s+(?'wildcard'.*)";
    
                foreach (string input in inputs)
                {
                    Boolean valid = false;
    
                    Match match = Regex.Match(input, pattern);
                    if (match.Success)
                    {
                        string wildcard = match.Groups["wildcard"].Value;
                        int percentCount = wildcard.Where(x => x == '%').Count();
                        if ((percentCount == 1) || (percentCount == 2))
                        {
                            string wildcardPattern = "^('%A%'|'%A'|'A%')$";
                            Match match2 = Regex.Match(wildcard, wildcardPattern);
                            if (match2.Success) valid = true;
                        }
                    }
                    Console.WriteLine("Success = '{0}', string = '{1}'", valid ? "true" : "false", input);
                }
                Console.ReadLine();
            }
        }
    }
    

    【讨论】:

    • 谢谢!我现在想缩小范围,拜托。我只是想验证输入字符串。规则是 1) 必须有一个值 2) 只允许 somestring 或 %somestring 或 somstring% 或 %somestring%
    • 来自:"^('%A%'|'%A'|'A%')$";致:@"^('%\w+%'|'%\w+'|'\w+%')$";我假设您仍然需要单引号。
    猜你喜欢
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2020-02-11
    相关资源
    最近更新 更多