为什么 javascript matches() 返回多个项目

Why does javascript matches() return multiple items

本文关键字:项目 返回 javascript matches 为什么      更新时间:2023-09-26

我正在对我解析的文件进行 iframe 上传,当我查看 iframe 的.innerHTML时,我的响应在 pre 标记中。 我只想获取没有pre标签的数据。 我想,既然这是我们在这里做的一次性事情,并且我们在数据服务器端验证,我知道我的数据将只有开始和结束pre标签。

在这个正则表达式测试器上:http://www.regular-expressions.info/javascriptexample.html,

我使用这个正则表达式:

<pre>(.*?)</pre>

在我的测试数据上:

<pre>{test : foo}</pre>

在这个网站上,当我要求它"显示匹配"时,它会给我回报

{test:foo}

但是当我在我的实际代码中尝试这样做时,我确实:

var iframeContents = $("#postiframe").get(0).contentWindow.document.body.innerHTML;
var re = new RegExp("<pre>(.*?)</pre>");
var results = iframeContents.match(re);
console.log(iframeContents);
console.log("results");
console.log(results);

注意:我不得不使用new RegExp样式,因为我无法弄清楚如何在 Typescript 中创建文字正则表达式。 无论如何,当我记录结果时,

results[0]看起来像:

<pre>{test : foo}</pre>

results[1]看起来像:

{test:foo}

这样得到两场比赛是正确的吗?

.match() 返回一个数组。

返回结果中的[0]是整个匹配项。

[1] 是第一个匹配的组(正则表达式中括号中的内容)

[2]是第二个匹配组

等等...

如果要与匹配的组获得多个匹配项,则可以在正则表达式上使用g标志并使用多个调用来.exec()

var iframeContents = $("#postiframe").get(0).contentWindow.document.body.innerHTML;
var re = new RegExp("<pre>(.*?)</pre>", "g");
var matches;
while (matches = re.exec(iframeContents)) {
    // matches[1] will be each successive block of text between the pre tags
    console.log(matches[1]);
}

是的,这是正确的。

结果是一个数组,其中第一项是与整个正则表达式匹配的字符串部分,以下项是使用括号捕获的值。

有几件事:

  • 要使用正则表达式文字,您需要使用 ' 转义/,以便'/
  • 使用/g以便只获得结果。

因此:

var iframeContents = '<pre>{test : foo}</pre>'
var re = /<pre>(.*?)<'/pre>/g; // you need to escape "/", to get only results use '/g'
var results = iframeContents.match(re);
console.log("results",results);

在此处查看实时示例