Wildcard string comparison

I found that there is no built-in wildcard comparison in .NET. Or I have not found. Anyway I have created an extension method for a string to compare with a wildcard pattern which uses the ‘*’ and ‘?’ wildcards. The code is below

/// Extensions for the wildcard comparison
public static class WildcardExtensions
    /// This method compares a string with wildcard pattern
    /// A string
    /// A wildcard pattern
    /// True if a string matches a pattern otherwise false
    public static bool WildcardCompare(this string input, string  wildcardPattern)
        var escaped = Regex.Escape(wildcardPattern);
        escaped = escaped.Replace("\\*", ".*").Replace("\\?", ".?");
        escaped = String.Concat("^", escaped, "$");
        return Regex.IsMatch(input, escaped);
This entry was posted in .NET, C#, Regular Expressions. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s