【问题标题】:RegExp match with lastIndex results in infinite loopRegExp 与 lastIndex 匹配导致无限循环
【发布时间】:2018-12-15 20:01:04
【问题描述】:

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

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 将等于“我的名字是”。当我调用console.log(doStuff(firstblock)) 时,将没有匹配项,因此不会执行while 循环,它会在屏幕上打印“my name is”。怎么了?

我将附上一个示例,但它可能会导致您的浏览器选项卡崩溃。被警告。 :)

【问题讨论】:

    标签: javascript regex loops while-loop infinite-loop


    【解决方案1】:

    您在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)

    【讨论】:

    • 这行得通……但有一个问题。如果你有一个类似“嗨,我的名字是嗨,嗨,我的名字是 Ben Hi”这样的字符串,它只会记录第一个匹配项。
    猜你喜欢
    • 2020-08-27
    • 2021-05-07
    • 2012-08-24
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多