本文介绍了Javascript正则表达式 - exec无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用正则表达式获取链接文本。可能有几个链接可能与模式匹配,我想要到最远的第四个。这是我的JS代码:

I'm trying to get a link text using regex. there are possibly several links that may match the pattern and I want to get the furthest one until the 4th. Here is my JS code:

var level=1;
while ( _match = /<a href="http:\/\/www.mysite.com\/x\/(?:.*)>(.*)<\/a>/img.exec(_html)){
    if (level < 5)  (_anchor_text=_match[1]);
    level ++;
}

问题是此代码在IE上进入无限循环(在FF上运行良好),尽管模式存在。任何帮助表示赞赏。

The problem is that this code enters infinite loop on IE (works well on FF), although the pattern exists. Any help is appreciated.

推荐答案

RegExp.exec ,我相信,使用属性并不断修改它以使全局组捕获成为可能;要使它工作,您需要有一个正则表达式。目前你是在每次迭代中创建一个新的,所以它不起作用...

RegExp.exec, I believe, makes use of the lastIndex property and continually modifies it to make things like "global group capturing" possible; for it to work you need to have a single regular expression. Currently you're creating a new one on every iteration so it won't work...

试试这个:

var level = 1;
var pattern = /<a href="http:\/\/www.mysite.com\/x\/(?:.*)>(.*)<\/a>/img;
var _match;
while ( _match = pattern.exec(_html)){
     if (level < 5)  (_anchor_text=_match[1]);
     level ++;
}

这篇关于Javascript正则表达式 - exec无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:50