我有一个字符串看起来像这样:
/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.match
或string.split
函数是否可以实现?
答案 0 :(得分:2)
您也可以使用split
和reduce
。
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
<强>演示强>
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;
修改强>
使用@ 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