我正在对我解析的文件执行 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]);
}
关于javascript - 为什么 javascript matches() 返回多个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19947120/