The most accepted answer works fine for most cases and can be used in most scenarios:
"^" + Regex.Escape(pattern).Replace(@"\*", ".*").Replace(@"\?", ".") +"$";
However if you allow escaping in you input wildcard pattern, e.g. "find \*
", meaning you want to search for a string "find *
" with asterisk, it won't work. The already escaped * will be escaped to "\\\\\\*
" and after replacing we have "^value\\ with\\\\.*$
", which is wrong.
The following code (which for sure can be optimized and rewritten) handles that special case:
public static string WildcardToRegex(string wildcard) { var sb = new StringBuilder(); for (var i = 0; i < wildcard.Length; i++) { // If wildcard has an escaped \* or \?, preserve it like it is in the Regex expression var character = wildcard[i]; if (character == '\\'&& i < wildcard.Length - 1) { if (wildcard[i + 1] == '*') { sb.Append("\\*"); i++; continue; } if (wildcard[i + 1] == '?') { sb.Append("\\?"); i++; continue; } } switch (character) { // If it's unescaped * or ?, change it to Regex equivalents. Add more wildcard characters (like []) if you need to support them. case '*': sb.Append(".*"); break; case '?': sb.Append('.'); break; default: //// Escape all other symbols because wildcard could contain Regex special symbols like '.' sb.Append(Regex.Escape(character.ToString())); break; } } return $"^{sb}$"; }
Solution for the problem just with Regex substitutions is proposed here https://stackoverflow.com/a/15275806/1105564