Last active
December 17, 2015 01:59
-
-
Save Larry57/5532148 to your computer and use it in GitHub Desktop.
Change a wildcard to a RegEx
http://stackoverflow.com/questions/6907720/need-to-perform-wildcard-etc-search-on-a-string-using-regex
http://www.codeproject.com/Articles/11556/Converting-Wildcards-to-Regexes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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("\\?", ".") + "$"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment