2013-02-13 124 views
2

我需要比較幾個字符串與eachother。比較字符串和通配符

我有一個通配符'%'可以代替任何數字(數字可以是任何大小)。

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; 
+0

使用正則表達式匹配字符串 – 2013-02-13 14:02:39

+1

您是否在這個問題上花費了精力?你有沒有試過_anything_? – 2013-02-13 14:02:53

+1

而你的問題是...? – ken2k 2013-02-13 14:03:41

回答

3

這裏是你如何爲包含代表數字和通配符的任何兩個字符串做號碼:

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; 
    } 
2

怎麼做類似的東西..一個非常迅速,大致寫的例子,但它的工作原理

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; 
    } 
} 
+0

微調和防錯絕對可能和建議 – Ingo 2013-02-13 14:26:05