user1029697
user1029697

Reputation: 150

Compare strings with a wildcard

I need to compare a couple of strings with eachother.

I have a wildcard character '%' that can substitute any number (the number can be of any size).

string str1 = "STRUCT[1].VARSTRUCT[10].VAR[1]";
string str2 = "STRUCT[%].VARSTRUCT[%].VAR[%]";
string str3 = "STRUCT[%].VARSTRUCT[%].VAR[2]";

CompareStrings(str1, str2); // Should return TRUE;
CompareStrings(str2, str3); // Should return TRUE;
CompareStrings(str1, str3); // SHould return FALSE;

Upvotes: 2

Views: 2877

Answers (2)

Ivan Golović
Ivan Golović

Reputation: 8832

Here is how you can do it for any two strings containing numbers and wildcards that represent numbers:

    private static bool CompareStrings(string str1, string str2)
    {
        var ar1 = Regex.Matches(str1, @"[\d%]+").Cast<Match>().Select(m => m.Value).ToArray();
        var ar2 = Regex.Matches(str2, @"[\d%]+").Cast<Match>().Select(m => m.Value).ToArray();

        if (ar1.Length != ar2.Length)
            return false;

        // Check wildcards and numbers
        for (int i = 0; i < ar1.Length; i++)
            if (ar1[i] != ar2[i] && ar1[i] != "%" && ar2[i] != "%")
                return false;

        // Remove wildcards and numbers to check the other characters
        if (Regex.Replace(str1, @"[\d%]+", String.Empty) != Regex.Replace(str2, @"[\d%]+", String.Empty))
            return false;

       return true;
    }

Upvotes: 3

Ingo
Ingo

Reputation: 1815

a pretty quick and roughly written example of how to do something like that.. but it works

class Program
{
    static void Main(string[] args)
    {

        string str1 = "STRUCT[1].VARSTRUCT[10].VAR[1]";
        string str2 = "STRUCT[%].VARSTRUCT[%].VAR[%]";
        string str3 = "STRUCT[%].VARSTRUCT[%].VAR[2]";

        Console.WriteLine("str1 - str2: " + SpecialComparers.AreEqual(str1, str2));
        Console.WriteLine("str2 - str3: " + SpecialComparers.AreEqual(str2, str3));
        Console.WriteLine("str1 - str3: " + SpecialComparers.AreEqual(str1, str3));

    }
}

class SpecialComparers
{
    public static bool AreEqual(String in1, String in2)
    {
        Regex re = new Regex(@"STRUCT\[(\d+|%)\]\.VARSTRUCT\[(\d+|%)\]\.VAR\[(\d+|%)\]");

        var values1 = re.Match(in1).Groups;
        var values2 = re.Match(in2).Groups;

        if (values1.Count != values2.Count) return false;

        for (int i = 1; i <= values1.Count; i++ )
        {
            if (!values1[i].ToString().Equals(values2[i].ToString())
                && !values1[i].ToString().Equals("%")
                && !values2[i].ToString().Equals("%")
            )
                return false;
        }
        return true;
    }
}

Upvotes: 2

Related Questions