簡體   English   中英

使用正則表達式比較兩個字符串

[英]Compare two strings using 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 );
}

更好的解決方案是Levenshtein單詞距離算法。 一些C#示例:

從匹配的字符,您還可以計算百分比。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM