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 解决wanted1

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 回答