Archive for May, 2010

Convert DOS wildcards to Regex search pattern (C#)

Saturday, May 8th, 2010

Based on Codekeep by Stephen Smith. Additionally I escape backslash:

public static string WildcardToRegex(string pattern)
{
    return ("^" +
         pattern.Replace(@"\", @"\\")
         .Replace("(", @"\(")
         .Replace(")", @"\)")
         .Replace(".", @"\.")
         .Replace("*", "(.*)")
         .Replace("?", "(.{1,1})"));
        }
}

Here some testcode:

string[] texts = new string[]
{
    @"\\VirtualDrive\Test1.mp3",
    @"\\VirtualDrive\Test2.mp3",
    @"\\VirtualDrive\Test3.bin"
};

string wildCards = @"\\VirtualDrive\*.mp3";
string pattern = WildcardToRegex(wildCards);

string[] result =
    (from t in texts
    where RegularExpressions.Regex.IsMatch(t, pattern, RegexOptions.IgnoreCase)
    select t).ToArray();

UnitTest.Test(result.Length == 2);
UnitTest.Test(result[0] == texts[0]);
UnitTest.Test(result[1] == texts[1]);