下面的代码总是导致无限循环,我不知道为什么。
var regex1 = /Hi([^]*?)Hi/g
var str = `
Hi my name is Hi
`;
function doStuff(str) {
var lastMatchIndex = 0
while ((m = regex1.exec(str)) !== null) {
console.log("it's not null")
//firstblock is the content between the 2 hi's
var firstblock = m[1] || ""
if (firstblock !== "") {
console.log(doStuff(firstblock))
}
}
return str
}
doStuff(str)
我会假设 while 循环会出现一次,并且 firstblock
会等于“my name is”。当我调用 console.log(doStuff(firstblock))
时,不会有匹配项,因此 while 循环不会执行,它会在屏幕上打印“我的名字是”。出了什么问题?
我将附上一个示例,但它可能会使您的浏览器选项卡崩溃。被警告。 :)
最佳答案
您在 if
条件中缺少 return;
以防止外部递归函数的无限循环。 console.log(doStuff(firstblock))
将第二次调用 doStuff
函数,然后第二次调用将简单地返回 str
。控制被传递给调用递归函数,现在该函数需要将控制返回给 doStuff(str)
,否则 while
循环将无限执行。
var regex1 = /Hi([^]*?)Hi/g
var str = `Hi my name is Hi`;
function doStuff(str) {
var lastMatchIndex = 0
while ((m = regex1.exec(str)) !== null) {
console.log("it's not null")
//firstblock is the content between the 2 hi's
var firstblock = m[1] || ""
if (firstblock !== "") {
console.log(doStuff(firstblock));
return;
}
}
return str
}
doStuff(str)
关于javascript - RegExp 与 lastIndex 匹配导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51223462/