我需要相互比较几个字符串。
我有一个可以替换任何数字的通配符'%'(数字可以是任意大小)。
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 :(得分: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;
}
答案 1 :(得分: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;
}
}