1

特定の文字列を指定して、単語に最も近い一致を見つけようとしています。次に例を示します。

だから私は持っているでしょう:

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

ご覧のとおり、シーケンス マッチングでのみ文字を取得したいので、共通のシーケンスでのみ取得し、両方に文字があるためではありませjoshuaん。johnjojohh

以下を使用して、正規表現でそれを試しました。

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

一致する最初の文字のみを一致させる方法はありますか?

実装にはjavascriptを使用します

それが理にかなっていることを願っています

前もって感謝します

4

5 に答える 5

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);

デモ: http://jsfiddle.net/jMuDm/

于 2012-06-15T09:18:57.993 に答える
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

于 2012-06-15T09:46:07.917 に答える
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、2 番目の文字列のような式が作成され、最初の文字列に適用されます。それがあまり意味をなさないというわけではありません。

于 2012-06-15T09:55:47.377 に答える
0

正規表現ではこれを行うことはできません。両方の文字列をループしてインデックスを比較しないのはなぜですか? 同じインデックスで異なる値の文字にヒットするまで、文字を選択できます。

于 2012-06-15T09:18:18.320 に答える
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/

于 2012-06-15T09:40:54.730 に答える