Click here to Skip to main content
11,565,672 members (47,769 online)
Click here to Skip to main content

Converting Wildcards to Regexes

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

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:

  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(
 System.Environment.GetFolderPath(
 Environment.SpecialFolder.Personal));

// 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)
 if(wildcard.IsMatch(file))
  Console.WriteLine(file);

License

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

Share

About the Author

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

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 5 Pin
Christopher Drake2-Jan-13 9:05
memberChristopher Drake2-Jan-13 9:05 
GeneralMy vote of 5 Pin
Member 892678823-Sep-12 23:33
memberMember 892678823-Sep-12 23:33 
QuestionDoes not work with *.* Pin
guest2323113-Sep-12 3:23
memberguest2323113-Sep-12 3:23 
GeneralMy vote of 5 Pin
Kuthuparakkal12-Sep-12 17:03
memberKuthuparakkal12-Sep-12 17:03 
QuestionWord wild card matching behavior a little different from this Pin
weciii2-Mar-12 5:21
memberweciii2-Mar-12 5:21 
GeneralMy vote of 5 Pin
vet0n23-Feb-12 21:46
membervet0n23-Feb-12 21:46 
SuggestionAdding More Static Methods Pin
Sina Iravanian14-Dec-11 2:21
memberSina Iravanian14-Dec-11 2:21 
QuestionRe: Adding More Static Methods Pin
DontSailBackwards6-May-13 14:47
memberDontSailBackwards6-May-13 14:47 
AnswerRe: Adding More Static Methods Pin
drzaus1319-Sep-13 4:41
memberdrzaus1319-Sep-13 4:41 
GeneralMy vote of 5 Pin
Nagy Vilmos8-Nov-10 2:24
memberNagy Vilmos8-Nov-10 2:24 
Generalbug?? with '.' Pin
alchemy916-Nov-09 4:07
memberalchemy916-Nov-09 4:07 
GeneralRe: bug?? with '.' Pin
Steve Kutnar2-Sep-10 6:28
memberSteve Kutnar2-Sep-10 6:28 
QuestionHow to add other chars - [A-Z] [modified] Pin
boopathi_tpgit20-Oct-09 2:22
memberboopathi_tpgit20-Oct-09 2:22 
GeneralDifference between httphandlers and httpmodules Pin
gaurav200720-Jun-08 0:20
membergaurav200720-Jun-08 0:20 
GeneralRe: Difference between httphandlers and httpmodules Pin
reinux20-Jun-08 6:24
memberreinux20-Jun-08 6:24 
NewsThere's a new version of the RegEx Tester Tool ! Pin
BucanerO_Slacker1-Mar-08 23:18
memberBucanerO_Slacker1-Mar-08 23:18 
GeneralSmall suggestion Pin
Davide Icardi16-Dec-07 22:12
memberDavide Icardi16-Dec-07 22:12 
GeneralRe: Small suggestion Pin
philippe dykmans31-May-08 15:39
memberphilippe dykmans31-May-08 15:39 
GeneralCorrection... Pin
philippe dykmans31-May-08 15:45
memberphilippe dykmans31-May-08 15:45 
GeneralRe: Correction... Pin
Davide Icardi1-Jun-08 13:19
memberDavide Icardi1-Jun-08 13:19 
GeneralRe: Small suggestion Pin
sssw285-Mar-11 21:25
membersssw285-Mar-11 21:25 
GeneralSimple, yet good Pin
norm .net16-May-07 22:33
membernorm .net16-May-07 22:33 
GeneralRe: Simple, yet good Pin
reinux17-May-07 5:32
memberreinux17-May-07 5:32 
GeneralJust what I was looking for. Pin
Ryan McFarren12-Apr-07 7:55
memberRyan McFarren12-Apr-07 7:55 
GeneralRe: Just what I was looking for. Pin
reinux12-Apr-07 13:24
memberreinux12-Apr-07 13:24 
GeneralNICE Pin
Ben Allfree10-Mar-07 5:10
memberBen Allfree10-Mar-07 5:10 
GeneralRe: NICE Pin
reinux10-Mar-07 12:24
memberreinux10-Mar-07 12:24 
QuestionDoesnt work with input string containing meta characters Pin
skk-ws31-Jan-06 6:41
memberskk-ws31-Jan-06 6:41 
AnswerRe: Doesnt work with input string containing meta characters Pin
reinux1-Feb-06 19:03
memberreinux1-Feb-06 19:03 
AnswerRe: Doesnt work with input string containing meta characters Pin
reinux26-Mar-06 11:22
memberreinux26-Mar-06 11:22 
AnswerRe: Doesnt work with input string containing meta characters Pin
N3croman12-Jan-11 1:13
memberN3croman12-Jan-11 1:13 
QuestionA small improvement? Pin
Jim Parsells16-Sep-05 10:40
memberJim Parsells16-Sep-05 10:40 
AnswerRe: A small improvement? Pin
Jim Parsells16-Sep-05 16:35
memberJim Parsells16-Sep-05 16:35 
GeneralRe: A small improvement? Pin
reinux16-Sep-05 20:56
memberreinux16-Sep-05 20:56 
GeneralRe: A small improvement? Pin
Jim Parsells17-Sep-05 5:09
memberJim Parsells17-Sep-05 5:09 
GeneralRe: A small improvement? Pin
reinux17-Sep-05 11:48
memberreinux17-Sep-05 11:48 
Hmm it'd be interesting to produce IL based on regexes the way RegexOptions.Compile does... that'd beat everything, though probably not for much gains Laugh | :laugh:
AnswerRe: A small improvement? Pin
reinux16-Sep-05 20:59
memberreinux16-Sep-05 20:59 
GeneraliNice trick :) Pin
Pop Catalin15-Sep-05 20:49
memberPop Catalin15-Sep-05 20:49 
GeneralRe: iNice trick :) Pin
reinux16-Sep-05 21:14
memberreinux16-Sep-05 21: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
Web04 | 2.8.150624.2 | Last Updated 15 Sep 2005
Article Copyright 2005 by Rei Miyasaka
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid