Quantcast
Viewing all articles
Browse latest Browse all 12

Answer by Tejasvi Hegde for Need to perform Wildcard (*,?, etc) search on a string using Regex

I think @Dmitri has nice solution at Matching strings with wildcardhttps://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)

Viewing all articles
Browse latest Browse all 12

Trending Articles