正则表达式全局匹配项直到分隔符,结果没有term / delimiter

时间:2012-12-11 08:42:33

标签: javascript regex match

我的字符串包含由;\n分隔的(FUDI)消息。我尝试提取以某个字符串开头的所有消息。

以下正则表达式找到正确的消息,但仍包括分隔符和搜索词。

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. 如何删除分隔符(want1)?
  2. 是否有可能只返回搜索词之后的所有内容(want2)?
  3. 我是一名正则表达式初学者,所以非常感谢任何帮助。

    编辑:使用/ 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"]
    

1 个答案:

答案 0 :(得分: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;
}