|
using System.Text;
using System.Text.RegularExpressions;
namespace FileFind
{
/// <summary>
/// Represents a wildcard running on the
/// <see cref="System.Text.RegularExpressions"/> engine.
/// /// Credit for this class belongs to reinux as published in the
/// "Converting Wildcards to Regexes" article at http://www.codeproject.com/KB/recipes/wildcardtoregex.aspx
/// </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 wildcard)
{
StringBuilder sb = new StringBuilder(wildcard.Length + 8);
sb.Append("^");
for (int i = 0; i < wildcard.Length; i++)
{
char c = wildcard[i]; switch (c)
{
case '*':
sb.Append(".*"); break;
case '?':
sb.Append("."); break;
case '\\':
if (i < wildcard.Length - 1)
sb.Append(Regex.Escape(wildcard[++i].ToString()));
break;
default:
sb.Append(Regex.Escape(wildcard[i].ToString()));
break;
}
}
sb.Append("$");
return sb.ToString();
} //ends public static string WildcardToRegex(...
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.