Javascript 仅匹配给定字符串中单词序列中的字符
我试图通过给出一个特定的字符串来找到一个单词最接近的匹配项,例如: 所以我会:Javascript 仅匹配给定字符串中单词序列中的字符,javascript,regex,string-matching,charsequence,Javascript,Regex,String Matching,Charsequence,我试图通过给出一个特定的字符串来找到一个单词最接近的匹配项,例如: 所以我会: "jonston" x "john" => "jo" //only "jo" is the part that matches "joshua" x "john" => "jo" "mark" x "marta" => "mar" 正如您所看到的,我只想检索序列匹配中的字符,这就是为什么joshua和john只有公共序列中的jo,而不是joh,因为两者都有字母h 我使用正则表达式尝试了以
"jonston" x "john" => "jo" //only "jo" is the part that matches
"joshua" x "john" => "jo"
"mark" x "marta" => "mar"
正如您所看到的,我只想检索序列匹配中的字符,这就是为什么joshua
和john
只有公共序列中的jo
,而不是joh
,因为两者都有字母h
我使用正则表达式尝试了以下方法:
"john".match(/["joshua"]+/) //=> outputs ["joh"] and not ["jo"]
我有没有办法只匹配第一个匹配的字符
我将使用javascript进行实现
我希望这是有道理的
提前感谢您不能用regex真正做到这一点。为什么不循环遍历这两个字符串并比较索引呢?您可以选择字符,直到在同一索引中使用不同的值点击字符。
var a=“john”;
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);
var b=“约书亚”;
var x=“”;
对于(变量i=0;i0)中断;
如果(a[i]==b[i])x+=a[i];
否则,如果(x!=“”)中断;
}
控制台日志(x);
演示:我会在递归函数中这样做:
var commonFirstChars = "john".commonFirstChars("joshua");
// "john".commonFirstChars("joshua") === "joshua".commonFirstChars("john")
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];
}
编辑:更新了示例,使其更具可读性
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'));
小提琴(更新):另一种解决方案:
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];
}
};
}
这将返回:
jo
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") // ""
这将从第二个字符串创建一个类似于
/^(j(o(h(n)?)?)?)?)/g的表达式,并将其应用于第一个字符串。不是说这很有意义,只是为了见鬼。哦,不,我的错,把逻辑读错了:p这对john
和mariejoe
though@FlorianMargaine我有没有办法只匹配那场比赛的第一个角色?我没说这回答了我说的问题,我刚才说这对约翰和玛丽乔不起作用,你回答说会的。我只是想把这个算法推进一点:——)@FlorianMargaine是的,但它是否适用于john
和mariejoe
?哦,好吧,假设我只是想从工程中获得一些乐趣。@sp00m:基本上是你的,但更简洁。