Introduction
Ever wondered how to do wildcards in .NET? It's not hard, all you have to do is use regular expressions. But it's not always easy to figure it out either. I found that I had to dig around for a while to figure out how to do it properly.
Even though regexes are a lot more powerful, wildcards are still good in situations where you can't expect the user to know or learn the cryptic syntax of regexes. The most obvious example is in the file search functionality of practically all OSs -- there aren't many that don't accept wildcards. I personally need wildcards to handle the HttpHandlers
tag in web.config files.
Note: This method is good enough for most uses, but if you need every ounce of performance with wildcards, here is a good place to start.
Using the Code
There are three steps to converting a wildcard to a regex:
- Escape the pattern to make it regex-safe. Wildcards use only
*
and ?
, so the rest of the text has to be converted to literals.
- Once escaped,
*
becomes \*
and ?
becomes \?
, so we have to convert \*
and \?
to their respective regex equivalents, .*
and .
.
- Prepend
^
and append $
to specify the beginning and end of the pattern.
So, here's the golden function:
public static string WildcardToRegex(string pattern)
{
return "^" + Regex.Escape(pattern).
Replace("\\*", ".*").
Replace("\\?", ".") + "$";
}
Just to make it look cool, I wrapped it in a Wildcard
class that inherits Regex
.
public class Wildcard : Regex
{
public Wildcard(string pattern)
: base(WildcardToRegex(pattern))
{
}
public Wildcard(string pattern, RegexOptions options)
: base(WildcardToRegex(pattern), options)
{
}
public static string WildcardToRegex(string pattern)
{
return "^" + Regex.Escape(pattern).
Replace("\\*", ".*").
Replace("\\?", ".") + "$";
}
}
You can use it like any other Regex
-- case-(in)sensitivity, string replacement, matching and all.
string[] files = System.IO.Directory.GetFiles(
System.Environment.GetFolderPath(
Environment.SpecialFolder.Personal));
Wildcard wildcard = new Wildcard("*.txt", RegexOptions.IgnoreCase);
foreach(string file in files)
if(wildcard.IsMatch(file))
Console.WriteLine(file);