2012-06-15 60 views
2

我试着给一个特定的字符串,例如找到一个字一个最接近的匹配匹配一个词的序列中的字符:从给定的字符串

,所以我将有:

"jonston" x "john" => "jo" //only "jo" is the part that matches 
"joshua" x "john" => "jo" 
"mark" x "marta" => "mar" 

,你可以看到,我只希望检索序列匹配的字符,这就是为什么joshuajohn只会有jo共同的序列,而不是joh因为两者有信h

我已经试过了正则表达式使用下列内容:

"john".match(/["joshua"]+/) //=> outputs ["joh"] and not ["jo"] 

有什么办法,我只能匹配第一个字符相匹配的?

我将使用JavaScript来实施

我希望是有道理的提前

回答

1
initLCS = function(a, b) { 
    for (var i = 0; i < a.length && a[i] == b[i]; i++); 
    return a.substr(0, i); 
} 


initLCS("jonston", "john") // jo 
initLCS("jonston", "j111") // j 
initLCS("xx", "yy") // "" 

如果你坚持使用正则表达式,它是这样的:

initLCS = function(a, b) { 

    function makeRe(x) { 
     return x.length ? "(" + x.shift() + makeRe(x) + ")?" : ""; 
    } 

    var re = new RegExp('^' + makeRe(b.split("")), "g"); 
    return a.match(re)[0]; 
} 

。这将创建第二个字符串像/^(j(o(h(n)?)?)?)?/g一个表达式,它适用于第一个。并不是说它很有意义,仅仅是为了它。

+0

不错的,+1 :) – sp00m

+0

@ sp00m:它本质上是你的,但更加浓缩。 – georg

0

谢谢你不能真正做到这一点与正则表达式。为什么不直接循环两个字符串并比较索引?您可以选择字符,直到您在同一个索引中使用不同的值创建字符。

1
var a = "john"; 
var b = "joshua"; 
var x = ""; 

for (var i = 0; i < a.length; i++) { 
    if (x == "" && i > 0) break; 
    else if (a[i] == b[i]) x += a[i]; 
    else if (x != "") break; 
} 

console.log(x); 

DEMO:http://jsfiddle.net/jMuDm/

+0

将给出'joh'。 –

+0

@FlorianMargaine怎么会来? – VisioN

+0

哦,不,我的不好,看错了逻辑:p虽然 –

0

我应该这样做在这样的递归函数:

编辑:更新为例,使其更具可读性。

var testWords = [ 
    ['ted', 'terminator'], 
    ['joe', 'john'], 
    ['foo', 'bar'] 
]; 

var matches = testWords.map(function(wordPair) { 
    return (function matchChars(word1, word2, matches) { 
     if (word1[0] !== word2[0]) { 
      return [wordPair[0], wordPair[1], matches]; 
     } 

     matches = matches || ''; 
     matches += word1[0]; 
     return matchChars(word1.slice(1), word2.slice(1), matches); 
    }(wordPair[0], wordPair[1])); 
}); 


console.log(matches.map(function(match) { return match.join(', '); }).join('\n')); 
​ 

小提琴(更新):http://jsfiddle.net/VU5QT/2/

1

又一解决方案:

if(typeof String.prototype.commonFirstChars !== 'function') { 
    String.prototype.commonFirstChars = function(s) { 
     var common = ""; 
     for(var i=0; i<this.length; i++) { 
      if(this[i] !== s[i]) { 
       return common; 
      } 
      common += this[i];   
     } 
    }; 
} 

您可以使用它像这样:

var commonFirstChars = "john".commonFirstChars("joshua"); 
// "john".commonFirstChars("joshua") === "joshua".commonFirstChars("john") 

这将返回:

jo

相关问题