且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用正则表达式查找Javascript中两个字符串之间的差异

更新时间:2022-11-12 10:03:16

正则表达式仅识别字符串是否与特定模式匹配.它们不够灵活,无法像您要求的那样进行比较.您必须采用第一个字符串并基于它构建常规语言来识别第二个字符串,然后使用匹配组获取第二个字符串的其他部分并将它们连接在一起.这是一些以可读的方式完成我认为你想要的东西.

Regexes only recognize if a string matches a certain pattern. They're not flexible enough to do comparisons like you're asking for. You would have to take the first string and build a regular language based on it to recognize the second string, and then use match groups to grab the other parts of the second string and concatenate them together. Here's something that does what I think you want in a readable way.

//assuming "b" contains a subsequence containing 
//all of the letters in "a" in the same order
function getDifference(a, b)
{
    var i = 0;
    var j = 0;
    var result = "";

    while (j < b.length)
    {
        if (a[i] != b[j] || i == a.length)
            result += b[j];
        else
            i++;
        j++;
    }
    return result;
}

console.log(getDifference("test fly", "test xy flry"));

这是一个 jsfiddle:http://jsfiddle.net/d4rcuxw9/1/

Here's a jsfiddle for it: http://jsfiddle.net/d4rcuxw9/1/