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

Scott picture Scott · Aug 2, 2011 · Viewed 118.9k times · Source

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

string input = "Message";
string pattern = "d*";
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);

if (regex.IsMatch(input))
{
    MessageBox.Show("Found");
}
else
{
    MessageBox.Show("Not Found");
}

With the above code "Found" block is hitting but actually it should not!

If my pattern is "e*" then only "Found" should hit.

My understanding or requirement is d* search should find the text containing "d" followed by any characters.

Should I change my pattern as "d.*" and "e.*"? Is there any support in .NET for Wild Card which internally does it while using Regex class?

Answer

Gabe picture Gabe · Aug 2, 2011

From http://www.codeproject.com/KB/recipes/wildcardtoregex.aspx:

public static string WildcardToRegex(string pattern)
{
    return "^" + Regex.Escape(pattern)
                      .Replace(@"\*", ".*")
                      .Replace(@"\?", ".")
               + "$";
}

So something like foo*.xls? will get transformed to ^foo.*\.xls.$.