简体   繁体   中英

Why does this cause a browser lock(infinite loop I presume)

Why is this statement hanging?

while ((matched = rx.exec(text)) != null) {
  while((m = rx.exec(matched[0])) != null) {

  }
}

It's hard to know for sure without seeing the actual values of text and rx and what actually happens in this loop depends upon the content of those, but one theory is that the .exec() method with the "g" flag maintains state from one call to the next precisely so that you can call it repeatedly in a single loop. For your outer loop to work properly, that state must be preserved from one iteration of the outer loop to the next.

But, when you take that same regex object and use it to search something different in the inner loop, that state is not going to be preserved properly - the outer state in the rx object is going to be disturbed by the inner loop which is also using the same rx object.

Your double loop would probably work if you used separate regex objects for each loop like this:

while ((matched = rx1.exec(text)) != null) {
  while((m = rx2.exec(matched[0])) != null) {

  }
}

They would need to be truly separate regex objects, not references to the same regex object.

In addition, matched[0] contains the whole match from the outer search so you've just matched matched[0] in the outer loop with your regex and then you ask to match again on the exact same thing you just matched with the same regex. Why? What are you trying to accomplish? It doesn't seem like the inner loop would do anything useful.

As with many questions here on SO, if you back up and tell us what you're really trying to accomplish, we could probably provide more useful info towards actually solving your real problem.

In any case, my first three paragraphs explain why this could easily be an infinite loop.

match matched[0]始终包含整个匹配项,因此内部循环可能永远不会终止。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM