Click here to Skip to main content
Click here to Skip to main content

Converting Wildcards to Regexes

, 15 Sep 2005
Rate this:
Please Sign up or sign in to vote.
Ever wondered how to do wildcards in C#?


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:

  1. Escape the pattern to make it regex-safe. Wildcards use only * and ?, so the rest of the text has to be converted to literals.
  2. Once escaped, * becomes \* and ? becomes \?, so we have to convert \* and \? to their respective regex equivalents, .* and ..
  3. 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.

/// <summary>
/// Represents a wildcard running on the
/// <see cref="System.Text.RegularExpressions"/> engine.
/// </summary>
public class Wildcard : Regex
 /// <summary>
 /// Initializes a wildcard with the given search pattern.
 /// </summary>
 /// <param name="pattern">The wildcard pattern to match.</param>
 public Wildcard(string pattern)
  : base(WildcardToRegex(pattern))
 /// <summary>
 /// Initializes a wildcard with the given search pattern and options.
 /// </summary>
 /// <param name="pattern">The wildcard pattern to match.</param>
 /// <param name="options">A combination of one or more
 /// <see cref="System.Text.RegexOptions"/>.</param>
 public Wildcard(string pattern, RegexOptions options)
  : base(WildcardToRegex(pattern), options)
 /// <summary>
 /// Converts a wildcard to a regex.
 /// </summary>
 /// <param name="pattern">The wildcard pattern to convert.</param>
 /// <returns>A regex equivalent of the given wildcard.</returns>
 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.

// Get a list of files in the My Documents folder
string[] files = System.IO.Directory.GetFiles(

// Create a new wildcard to search for all
// .txt files, regardless of case
Wildcard wildcard = new Wildcard("*.txt", RegexOptions.IgnoreCase);

// Print all matching files
foreach(string file in files)


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Rei Miyasaka

Canada Canada
The cows are here to take me home now...

Comments and Discussions

AnswerRe: Doesnt work with input string containing meta characters PinmemberN3croman12-Jan-11 2:13 
QuestionA small improvement? PinmemberJim Parsells16-Sep-05 11:40 
AnswerRe: A small improvement? PinmemberJim Parsells16-Sep-05 17:35 
Inquiring minds might like to know that performing the equivalent file name pattern matching using the VB.Net Like operator does the same match in 60 per cent of the time. Regexs are very powerful, but not without a cost.
I assumed that there was a cost to using Regex for simple matches so I got inspired to try it out. Do each over 2700 file names (about 1300 matches) 100 times, throw out the top & bottom 10 scores -- Like wins by 40 per cent.
Average times: Ignoring case in both, compiling the Regex on initiation of
wildcard class.
Like =.0083 seconds
Regex=.0132 seconds
Either one gets over 2700 comparisons very quickly.
Jim Parsells
GeneralRe: A small improvement? Pinmemberreinux16-Sep-05 21:56 
GeneralRe: A small improvement? PinmemberJim Parsells17-Sep-05 6:09 
GeneralRe: A small improvement? Pinmemberreinux17-Sep-05 12:48 
AnswerRe: A small improvement? Pinmemberreinux16-Sep-05 21:59 
GeneraliNice trick :) PinmemberPop Catalin15-Sep-05 21:49 
GeneralRe: iNice trick :) Pinmemberreinux16-Sep-05 22:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150327.1 | Last Updated 15 Sep 2005
Article Copyright 2005 by Rei Miyasaka
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid