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

后端 未结 10 2454
执笔经年
执笔经年 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条回答
  •  猫巷女王i
    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;
    }
    

提交回复
热议问题