// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Text.RegularExpressions; namespace E { public class Wildcard { private Regex re; public Wildcard(string expr) { re = new Regex("^" + expr.Replace(@"\", @"\\").Replace(".", @"\.").Replace("*", @".*").Replace("?", @".") + "$", RegexOptions.Compiled | RegexOptions.IgnoreCase); } public bool IsMatch(string s) { return re.IsMatch(s); } } public class Program { public static void Main(string[] args) { Wildcard wc1 = new Wildcard("*.txt"); Console.WriteLine(wc1.IsMatch("foobar.txt")); Console.WriteLine(wc1.IsMatch("foobar.dat")); Console.WriteLine(wc1.IsMatch("foobar.txt_old")); Wildcard wc2 = new Wildcard("foo*.txt"); Console.WriteLine(wc2.IsMatch("foobar.txt")); Console.WriteLine(wc2.IsMatch("foobar.dat")); Console.WriteLine(wc2.IsMatch("foobar.txt_old")); Wildcard wc3 = new Wildcard(@"C:\foo*.txt"); Console.WriteLine(wc3.IsMatch(@"C:\foobar.txt")); Console.WriteLine(wc3.IsMatch(@"C:\foobar.dat")); Console.WriteLine(wc3.IsMatch(@"C:\foobar.txt_old")); Wildcard wc4 = new Wildcard(@"C:\foo?a?.txt"); Console.WriteLine(wc4.IsMatch(@"C:\foobar.txt")); Console.WriteLine(wc4.IsMatch(@"C:\foobar.dat")); Console.WriteLine(wc4.IsMatch(@"C:\foobarr.txt")); } } }