这个简单的代码应该替换一个基于regExp的子字符串,但奇怪的是,它似乎跳过了所有其他匹配。我很难弄清楚到底是什么问题。while是第三方法典的一部分,我宁愿不改变它。
var text = `
<!-- build:js[vendor0.js] -->
xx
<!-- /build -->
<!-- build:js[vendor1.js] -->
xx
<!-- /build -->
<!-- build:js[vendor2.js] -->
xx
<!-- /build -->
<!-- build:js[vendor3.js] -->
xx
<!-- /build -->
<!-- build:js[vendor4.js] -->
xx
<!-- /build -->
`
var regex = /<!-- build:([\s\S]*?)\[([\s\S]*?)] -->[\s\S]*?<!-- \/build -->/gm
var replacementFn = function(match, type, path) { return `REPLACED: ${type} - ${path}` }
// 3rd party code
while ((matches = regex.exec(text)) != null) {
var replacement = replacementFn.apply(null, matches)
text = text.replace(matches[0], replacement)
}
// end 3rd party code
console.log(text)
解决方案:从这里看,JS regex跳过每一场比赛似乎只是删除了解决的全局标志。
发布于 2020-03-04 23:46:51
RegExp是有状态的,这意味着对exec的调用“记住”了匹配的最后一个位置,并从那里开始下一次调用。您可能更希望使用String.prototype.match来避免调用RegExp.exec的有状态行为。
发布于 2020-03-04 23:46:59
如果您想要更改while循环,这可能会有所帮助。我会给出一个答案。使用replace。
var text = `
<!-- build:js[vendor0.js] -->
xx
<!-- /build -->
<!-- build:js[vendor1.js] -->
xx
<!-- /build -->
<!-- build:js[vendor2.js] -->
xx
<!-- /build -->
<!-- build:js[vendor3.js] -->
xx
<!-- /build -->
<!-- build:js[vendor4.js] -->
xx
<!-- /build -->
`;
var regex = /<!-- build:([\s\S]*?)\[([\s\S]*?)] -->[\s\S]*?<!-- \/build -->/gm
var replacement = function(match, type, path) {
return `REPLACED: ${type} - ${path}`;
}
console.log(text.replace(regex, replacement));
发布于 2020-03-04 23:50:36
//var regex = /<!-- build:([\s\S]*?)\[([\s\S]*?)] -->[\s\S]*?<!-- \/build -->/gm
var replacementFn = function(match, type, path) { return `REPLACED: ${type} - ${path}` }
// 3rd party code
while ((matches = /<!-- build:([\s\S]*?)\[([\s\S]*?)] -->[\s\S]*?<!-- \/build -->/gm.exec(text)) != null) {
var replacement = replacementFn.apply(null, matches)
text = text.replace(matches[0], replacement)
}
// end 3rd party code
console.log(text)必须为每个while循环创建一个新的Regex实例。
var regex = function(){
return /<!-- build:([\s\S]*?)\[([\s\S]*?)] -->[\s\S]*?<!-- \/build -->/gm
}
var replacementFn = function(match, type, path) { return `REPLACED: ${type} - ${path}` }
// 3rd party code
while ((matches = regex().exec(text)) != null) {
var replacement = replacementFn.apply(null, matches)
text = text.replace(matches[0], replacement)
}
// end 3rd party code
console.log(text)https://stackoverflow.com/questions/60536244
复制相似问题