Available for full time assignments: 01.04.2014

Wildcard Matching In C# Using Regular Expressions

WRITTEN BY Henrik Brinch - 07 March 2013

From my blog analytics I can see, quite many of you seeking methods for doing wildcard matching in C#.  You found my blog post from last year and is maybe not happy using a Visual Basic assembly for a simple wildcard match.

Obviously this is not the only method.  You can writer your own from thegound up, and for the fun of it - I began on such - but stopped on the half way.  Why do that, when you can achieve the same using regular expressions?

Many times, I get amazed of how many developers I meet that doesn't know regular expression or if they do, they don't use them.

I admit, you need to be some kind of a nerd or autistic of nature to know and utilize the full syntax.  For several years I've been using the absolutely outstanding tool called RegExBuddy.  It is a commercial tool (but hey, it's only 29.95 euro and its worth 100 times that!).  It enables you to visually create your regular expression and test them in the environment.  From then on you can paste it directly into
your C# program.

Ok, back on track:  Let's take the simpe wildcard matching characters "*" and "?", where "*" will match X number of characters and "?" will match exactly one character.  To make this "regular-expressionable", we need to convert the "*" and "?" characters to the regular expression syntax.  Further more we need to ensure, that any characters used doesn't collide with the regular expression syntax.

So basically, what we need is to convert the pattern string to a regular expression compatible string.   This is done with a series of standard string replaces.

The first replace, takes care of the "." character which is reserved.
The second replaces the "?" with the "." character, which is the equivalent to the "?" in our syntax.
The third is the "*", which converted to regular expression is ".*?".
The fourth escapes escaped characters.
And the last handles whitespace.

It is by no mean, a full finished version - but it demonstrates the principle.

public static class WildcardMatch
    #region Public Methods
    public static bool IsLike(string pattern, string text, bool caseSensitive=false)
        pattern = pattern.Replace(".", @"\.");
        pattern = pattern.Replace("?", ".");
        pattern = pattern.Replace("*", ".*?");
        pattern = pattern.Replace(@"\", @"\\");
        pattern = pattern.Replace(" ", @"\s");
        return new Regex(pattern, caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase).IsMatch(text);

comments powered by Disqus

Bookmark and Share

.NET / C# course - training
10 x 4 hrs., 10 participants
only DKK. 7.475,-/per. particpant
Read more here ...

View Henrik Brinch's profile on LinkedIn