Tim
Tim

Reputation: 2911

Compare Two Strings With Wildcards

I need to compare two strings, one of which uses '*' as a wildcard. I was thinking of using either an iterative or recursive method when I realized that RegEx would perform the task more quickly. Unfortunately, I am new to RegEx, and am not sure how to do this.

If I sent in the pattern "He**o", then "Hello" and "He7(o" should return true, but "Hhllo" should return false.

Upvotes: 3

Views: 9655

Answers (4)

Tariin
Tariin

Reputation: 1

That's exactly what I've done in php today. When you add this:

if (pattern[x] != '*' && compare[x] != '*')

Then both strings can have wildcards. (hope that && means logical AND like in php)

Upvotes: 0

Jonathan Carroll
Jonathan Carroll

Reputation: 870

Compare the strings by using the char index in a for loop. If the pattern char (wildcard) appears, ignore the comparison and move on to the next comparison.

private bool Compare(string pattern, string compare)
{
    if (pattern.Length != compare.Length)
        //strings don't match
        return false;

    for(int x = 0, x < pattern.Length, x++)
    {
        if (pattern[x] != '*')
        {
            if (pattern[x] != compare[x])
                return false;
        }
    }
    return true;
}

Upvotes: 2

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

Assuming that you mean * to be a single-character wildcard, the correct substitution in a Regex pattern is a dot (.):

string pattern = "He**o";
string regexPattern = pattern.Replace("*",".");

Regex.IsMatch("Hello",regexPattern); // true
Regex.IsMatch("He7)o",regexPattern); // true
Regex.IsMatch("he7)o",regexPattern); // false
Regex.IsMatch("he7)o",regexPattern, RegexOptions.IgnoreCase); // true

You might also want to anchor the pattern with ^ (start of string) and $ (end of string):

regexPattern = String.Format("^{0}$", pattern.Replace("*","."));

If you expect it to be able to parse input strings with special characters, you'll can escape all other characters like this:

string regexPattern = String.Join(".",pattern.Split("*".ToCharArray())
                                             .Select(s => Regex.Escape(s)).ToArray());

Upvotes: 4

Andr&#233; Secco
Andr&#233; Secco

Reputation: 71

Make Regex using "He..lo"

This is a case that will not be recognized

Regex r = new Regex("He..o");
string test = "Hhleo";
bool sucess = r.Match(a).Success;

This is a case that will be recognized

Regex r = new Regex("He..o");
string test = "He7)o";
bool sucess = r.Match(a).Success;

Upvotes: 1

Related Questions