Click here to Skip to main content
6,630,901 members and growing! (18,564 online)
Email Password   helpLost your password?
General Programming » Algorithms & Recipes » Regular Expressions     Intermediate

Converting Wildcards to Regexes

By reinux

Ever wondered how to do wildcards in C#?
C#, Windows, .NET CF, .NET, Mobile, Visual Studio, Dev
Posted:6 Sep 2005
Updated:15 Sep 2005
Views:47,523
Bookmarked:39 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
34 votes for this article.
Popularity: 6.68 Rating: 4.36 out of 5
3 votes, 8.8%
1
1 vote, 2.9%
2
1 vote, 2.9%
3
6 votes, 17.6%
4
23 votes, 67.6%
5

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

About the Author

reinux


Member
I wish I weren't so geeky... but my fingers won't stop coding! :(
Location: Canada Canada

Other popular Algorithms & Recipes articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 26 (Total in Forum: 26) (Refresh)FirstPrevNext
Generalbug?? with '.' Pinmemberalchemy95:07 16 Nov '09  
GeneralHow to add other chars - [A-Z] [modified] Pinmemberboopathi_tpgit3:22 20 Oct '09  
GeneralDifference between httphandlers and httpmodules Pinmembergaurav20071:20 20 Jun '08  
GeneralRe: Difference between httphandlers and httpmodules Pinmemberreinux7:24 20 Jun '08  
NewsThere's a new version of the RegEx Tester Tool ! PinmemberBucanerO_Slacker0:18 2 Mar '08  
GeneralSmall suggestion PinmemberDavide Icardi23:12 16 Dec '07  
GeneralRe: Small suggestion Pinmemberphilippe dykmans16:39 31 May '08  
GeneralCorrection... Pinmemberphilippe dykmans16:45 31 May '08  
GeneralRe: Correction... PinmemberDavide Icardi14:19 1 Jun '08  
GeneralSimple, yet good Pinmembernorm .net23:33 16 May '07  
GeneralRe: Simple, yet good Pinmemberreinux6:32 17 May '07  
GeneralJust what I was looking for. PinmemberRyan McFarren8:55 12 Apr '07  
GeneralRe: Just what I was looking for. Pinmemberreinux14:24 12 Apr '07  
GeneralNICE PinmemberBen Allfree6:10 10 Mar '07  
GeneralRe: NICE Pinmemberreinux13:24 10 Mar '07  
QuestionDoesnt work with input string containing meta characters Pinmemberskk-ws7:41 31 Jan '06  
AnswerRe: Doesnt work with input string containing meta characters Pinmemberreinux20:03 1 Feb '06  
AnswerRe: Doesnt work with input string containing meta characters Pinmemberreinux12:22 26 Mar '06  
GeneralA small improvement? PinmemberJim Parsells11:40 16 Sep '05  
GeneralRe: A small improvement? PinmemberJim Parsells17:35 16 Sep '05  
GeneralRe: A small improvement? Pinmemberreinux21:56 16 Sep '05  
GeneralRe: A small improvement? PinmemberJim Parsells6:09 17 Sep '05  
GeneralRe: A small improvement? Pinmemberreinux12:48 17 Sep '05  
GeneralRe: A small improvement? Pinmemberreinux21:59 16 Sep '05  
GeneraliNice trick :) PinmemberPop Catalin21:49 15 Sep '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 15 Sep 2005
Editor: Smitha Vijayan
Copyright 2005 by reinux
Everything else Copyright © CodeProject, 1999-2009
Web22 | Advertise on the Code Project