我有一个看起来像这样的字符串:
/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
函数?
最佳答案
您也可以使用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);
编辑
使用@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
关于javascript - 正则表达式:多次匹配相同的表达式并返回表达式前的完整字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49976724/