使用Regex比较两个字符串

时间:2013-06-08 08:47:26

标签: c# regex

我正在使用两个字符串来匹配这样的程序:

string s1= 5-4-6-+1-+1+1+3000+12+21-+1-+1-+1-+2-3-4-5-+1-+10+1-+1-+;
string s2= 6-+1-+1+1+3000+12+21-+1-+1-+1-+1-+1-+1+1-+1-+;

我将编写一个Regex匹配函数,它分别比较每个“+”之间的每个部分字符串,并计算匹配百分比,即每个字符串中发生的匹配数。 例如,在此示例中,我们有以下匹配项:

6

1

1

1

3000

12

21

1

1

1

--

1

--

1

1

在此示例中,匹配百分比为13 * 100/15 = 87%。

目前我正在使用下面的功能,但我认为它没有经过优化,使用Regex可能会更快。

public double MatchPercent(string s1, string s2) {
    int percent=0;
    User = s1.Split('+').ToArray();
    Policy = s2.Split('+').ToArray();

    for (int i = 0; i < s1.Length - 2; i++) {
        int[] U = User[i].Split('-').Where(a => a != "").Select(n => 
                      Convert.ToInt32(n)).Distinct().ToArray();
        int[] P = Policy[i].Split('-').Where(a => a != "").Select(n => 
                      Convert.ToInt32(n)).Distinct().ToArray();
        var Co = U.Intersect(P);
        if (Co.Count() > 0) {
            percent += 1;
        }
    }
    return Math.Round((percent) * 100 / s1.Length );
}

1 个答案:

答案 0 :(得分:2)

更好的解决方案是Levenshtein Word Distance算法。一些C#样本:

从匹配的字符中,您还可以计算百分比。

相关问题