Need to perform Wildcard (*,?, etc) search on a string using Regex

后端 未结 10 2272
执笔经年
执笔经年 2020-11-27 04:35

I need to perform Wildcard (*, ?, etc.) search on a string. This is what I have done:

string input = \"Message\";
string pattern =          


        
相关标签:
10条回答
  • 2020-11-27 05:16

    You must escape special Regex symbols in input wildcard pattern (for example pattern *.txt will equivalent to ^.*\.txt$) So slashes, braces and many special symbols must be replaced with @"\" + s, where s - special Regex symbol.

    0 讨论(0)
  • 2020-11-27 05:21

    You can do a simple wildcard mach without RegEx using a Visual Basic function called LikeString.

    using Microsoft.VisualBasic;
    using Microsoft.VisualBasic.CompilerServices;
    
    if (Operators.LikeString("This is just a test", "*just*", CompareMethod.Text))
    {
      Console.WriteLine("This matched!");
    }
    

    If you use CompareMethod.Text it will compare case-insensitive. For case-sensitive comparison, you can use CompareMethod.Binary.

    More info here: http://www.henrikbrinch.dk/Blog/2012/02/14/Wildcard-matching-in-C

    MSDN: http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.compilerservices.operators.likestring%28v=vs.100%29.ASPX

    0 讨论(0)
  • 2020-11-27 05:21

    I think @Dmitri has nice solution at Matching strings with wildcard https://stackoverflow.com/a/30300521/1726296

    Based on his solution, I have created two extension methods. (credit goes to him)

    May be helpful.

    public static String WildCardToRegular(this String value)
    {
            return "^" + Regex.Escape(value).Replace("\\?", ".").Replace("\\*", ".*") + "$";
    }
    
    public static bool WildCardMatch(this String value,string pattern,bool ignoreCase = true)
    {
            if (ignoreCase)
                return Regex.IsMatch(value, WildCardToRegular(pattern), RegexOptions.IgnoreCase);
    
            return Regex.IsMatch(value, WildCardToRegular(pattern));
    }
    

    Usage:

    string pattern = "file.*";
    
    var isMatched = "file.doc".WildCardMatch(pattern)
    

    or

    string xlsxFile = "file.xlsx"
    var isMatched = xlsxFile.WildCardMatch(pattern)
    
    0 讨论(0)
  • 2020-11-27 05:26

    All upper code is not correct to the end.

    This is because when searching zz*foo* or zz* you will not get correct results.

    And if you search "abcd*" in "abcd" in TotalCommander will he find a abcd file so all upper code is wrong.

    Here is the correct code.

    public string WildcardToRegex(string pattern)
    {             
        string result= Regex.Escape(pattern).
            Replace(@"\*", ".+?").
            Replace(@"\?", "."); 
    
        if (result.EndsWith(".+?"))
        {
            result = result.Remove(result.Length - 3, 3);
            result += ".*";
        }
    
        return result;
    }
    
    0 讨论(0)
提交回复
热议问题