javascript - RegExp 与 lastIndex 匹配导致无限循环

标签 javascript regex loops while-loop infinite-loop

下面的代码总是导致无限循环,我不知道为什么。

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/

相关文章:

javascript - 在较小的视口(viewport)中禁用 javascript 灯箱

javascript - 在应用 jquery.chosen 时,使用 jquery.validate 验证选择字段时会出现错误

c++ - tr/regex c++ 库 - 正则表达式模式的定义

python - Logparser 2.2 和 regex/sql

python - 我在构建剪刀石头布游戏时遇到问题(3 个版本中的最佳版本)

python - 检查药水使用情况的更好方法?

javascript - clearInterval 的问题

javascript - node js中的模块化编程

python - 如何通过忽略 Python 中特定大小写的模式来提取子字符串?

c# - 在步骤 C# 中将用户输入添加到数组?