正则表达式:多次匹配相同的表达式并在表达式之前返回完整的字符串

时间:2018-04-23 08:39:09

标签: javascript arrays regex

我有一个字符串看起来像这样:

 /a/b/entry/0/c/d/entry/0

我想将/entry/0/entry/[0-9]+相匹配。每次出现 单独并返回一个数组

 ["/a/b/entry/0/", "/a/b/entry/0/c/d/entry/0"]

表示字符串中/entry/[0-9]+的任意出现次数。 另请注意,我想将表达式保留在输出字符串中。

使用单个Regex表达式和JavaScript中的string.matchstring.split函数是否可以实现?

1 个答案:

答案 0 :(得分:2)

您也可以使用splitreduce

var input = "/a/b/entry/0/c/d/entry/0";
var output = input.split( /(?<=entry\/[0-9]+)/ )
                  .reduce( (a, c) => { 
                       a.push( (a[a.length - 1] || "") + c ); //push new item after appending c to last item in accumulator
                       return a; return accumulator
                  } ,[])//initialize accumulator

<强>演示

&#13;
&#13;
var input = "/a/b/entry/0/c/d/entry/0";
var output = input.split(/(?<=entry\/[0-9]+)/)
  .reduce((a, c) => {
    a.push((a[a.length - 1] || "") + c); //push new item after appending c to last item in accumulator
    return a;
    return accumulator
  }, []) //initialize accumulator

console.log(output);
&#13;
&#13;
&#13;

修改

使用@ Wiktor的建议match然后reduce

var input = "/a/b/entry/0/c/d/entry/0";
var output = (input.match(/.*?\/entry\/\d+(?:\/|$)/g) || []) //check for null
                  .reduce( (a, c) => { 
                       a.push( (a[a.length - 1] || "") + c ); //push new item after appending c to last item in accumulator
                       return a; return accumulator
                  } ,[])//initialize accumulator