2017-08-03 18 views
0

我想驗證輸入字符串。規則是以下:如何限制特定搜索的通配符

1)%somestring 2)somestring% 3)%somestring%

如果輸入字符串匹配用上面的格式,其真否則返回false。

注意:somestring不應該有%

回答

0

請嘗試遵循正則表達式。希望我正確解釋任務。

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(); 
     } 
    } 
} 
+0

謝謝!請現在我想縮小範圍。我只是想驗證輸入字符串。規則是1)必須有一個值2)只允許somestring或%somestring或somstring%或%somestring% – Vetriramasamy

+0

From:「^('%A%'|'%A'|'A%')$」;至:@「^('%\ w +%'|'%\ w +'|'\ w +%')$」;我假設你仍然需要單引號。 – jdweng

+0

謝謝!這對我有用:) – Vetriramasamy