3

我想匹配至少 n 个字符的字符串,比如 3。

例如,如果我有两个单词,如果两个单词有 3 个字符的公共子字符串,我想返回 true

即,如果我匹配California 和Unical,我希望得到正确,因为两者都将“Cal”作为公共字符串。

4

4 回答 4

0
function findCommonSubstring(s1, s2, n) {

    s1 = s1.toLowerCase();
    s2 = s2.toLowerCase();
    var min = s1.length < s2.length ? s1 : s2;
    var max = min == s1 ? s2 : s1;

    if(n <= 0 || n > min.length) {
        return false;
    }

    var substring;
    for(var i=0; i<=min.length-n; i++) {
        if(max.indexOf((substring = min.substring(i, i+n))) > -1) {
            return substring;
        }
    }

    return false;
}

称呼:

alert(findCommonSubstring("California", "Unical", 3));​

印刷:

cal

演示

于 2012-11-12T10:12:44.323 回答
0
function test(first,second,nl)
{
    first=first.toLowerCase();
    second=second.toLowerCase();

   if(first.length>second.length)
   {
       var len=first.length ;
   }
   else
   {
       var len=second.length;
       var t=first;
       first=second;
       second=t;
   }

   //var len=first.length>second.length?first.length:second.length;

   var count=0;
   while(len>=nl)
   {
       str=first.substr(count,nl);
       if(second.indexOf(str)!=-1)
       {
           return str;
           break;
       }
       count++;
       len--;
   }
   return false;        
}
 alert(test('Cal','unicbbl',4))  
 alert(test('California','unicali',3));
 alert(test('California','unicali',4));
[test here][1]


  [1]: http://jsfiddle.net/tuMRg/5/
于 2012-11-12T10:10:32.130 回答
0
function matchStrings(s1, s2, charnum) {
    var found = false;
    var i = 0;
    if ( charnum>0 && charnum<s2.length ) {
        s1=s1.toLowerCase();
        s2=s2.toLowerCase();
        for (i=0; i<=s2.length - charnum; i++) {
            if ( s1.indexOf(s2.substr(i, charnum)) > -1 ) {
                found = true;
                break;
            }
        }
    }
    return found;
}
于 2012-11-12T10:06:47.893 回答
0

以下是相当复杂的,但如果您从大型内容中搜索字符串,这是一个不错的选择。它首先过滤可能的匹配,然后测试这些可能性。

var atLeastMatch = function(search, content, atLeast) {
    var search = search,
        content = content,
        regex = new RegExp('[' + search + ']{' + atLeast + ',}', "i", "g"),
        possibleMatches = content.match(regex);

    for (var i = 0, j = possibleMatches.length; i < j; i++) {
        if (possibleMatches[i].length > atLeast) {
            for (var k = 0, l = possibleMatches[i].length - atLeast; k <= l; k++) {
                if ((new RegExp(possibleMatches[i].slice(k, k + atLeast), "i")).test(search)) {
                    return true;
                }

            }

        } else {
            if ((new RegExp(possibleMatches[i], "i")).test(search)) {
                return true;
            }

        }

    }

    return false;

}

console.log(atLeastMatch('California', 'Unical', 3));
于 2012-11-12T10:43:32.887 回答