0

私の文字列には、 で区切られた (FUDI) メッセージが含まれてい;\nます。特定の文字列で始まるすべてのメッセージを抽出しようとしています。

次の正規表現は正しいメッセージを見つけますが、区切り文字と検索語はまだ含まれています。

var input = 'a b;\n'
    + 'a b c;\n'
    + 'b;\n'
    + 'b c;\n'
    + 'b c d;\n';

function search(input, term){
    var regex = new RegExp('(^|;\n)' + term + '([^;\n]?)+', 'g');
    return input.match(regex);
}

console.log(search(input, 'a b'));
// current: ["a b", ";↵a b c"]
// wanted1: ["a b", "a b c"]
// wanted2: ["", "c"]

console.log(search(input, 'b'));
// current: [";↵b", ";↵b c", ";↵b c d"]
// wanted1: ["b", "b c", "b c d"]
// wanted2: ["", "c", "c d"]
  1. 区切り文字を削除するにはどうすればよいですか (wanted1)?
  2. 検索語 (wanted2) の後のすべてを返すことは可能ですか?

私は正規表現の初心者なので、どんな助けでも大歓迎です。

編集: /gm を使用して、want1 を解決します

var input = 'a b;\n'
    + 'a b c;\n'
    + 'b;\n'
    + 'b c;\n'
    + 'b c d;\n';

function search(input, term){
    var regex = new RegExp('^' + term + '([^;]*)', 'gm');
    return input.match(regex);
}

console.log(search(input, 'a b'));
// current: ["a b", "a b c"]
// wanted2: ["", "c"]

console.log(search(input, 'b'));
// current: ["b", "b c", "b c d"]
// wanted2: ["", "c", "c d"]
4

1 に答える 1

3

区切り文字を取り除くには、.split()代わりに を使用する必要があり.match()ます。

str.split(/;\n/);

あなたの例を使用して:

('a b;\n'
+ 'a b c;\n'
+ 'b;\n'
+ 'b c;\n'
+ 'b c d;\n').split(/;\n/)
// ["a b", "a b c", "b", "b c", "b c d", ""]

次に、一致を見つけるために、分割結果を繰り返し処理し、文字列の一致を行う必要があります。

function search(input, term)
{
    var inputs = input.split(/;\n/),
    res = [], pos;

    for (var i = 0, item; item = inputs[i]; ++i) {
        pos = item.indexOf(term);
        if (pos != -1) {
            // term matches the input, add the remainder to the result.
            res.push(item.substring(pos + term.length));
        }
    }
    return res;
}
于 2012-12-11T08:48:18.987 に答える