Regex帮助-包括,但不显示

Regex help - include, but not show

本文关键字:显示 帮助 -包括 Regex      更新时间:2023-09-26

我有一个this.responseText,这是凌乱的。试着把我需要的分开:

正文:

<html>
<head><title>Index of /browserify-view/build/source/pic/</title></head>
<body bgcolor="white">
<h1>Index of /browserify-view/build/source/pic/</h1><hr><pre><a href="../">../</a>
<a href="wd0c9af04bbf54efc9a2f7ba766a6694f2421b1dc.png">wd0c9af04bbf54efc9a2f7ba766a6694f2421b1dc..&gt;</a> 22-Jul-2016 22:29               65180
<a href="thumb-wd20f381801bb51.png">thumb-wd20f381801bb51.png;</a> 22-Jul-2016 22:33               10779
</pre><hr></body>
</html>

我怎样才能像这样分开:

wd0c9af04bbf54efc9a2f7ba766a6694f2421b1dc.png
thumb-wd20f381801bb51.png

这是迄今为止我看到的关于这个话题的最好的回答之一:RegEx匹配开放标签,除了XHTML自包含标签

如果你想做一些快速的事情,我会看看这样的东西(python):

<a[^>]+href="(?P<x>[^"]+)">

请注意,这是不好的做法,如果要在更大的规模上执行(除了this html之外的任何东西),我建议使用html解析器。从长远来看,这将节省很多时间。

首先,不要使用Regex这样做!

Regex是能够解析HTML!


使用javascript DOMParser代替:

var parser = new DOMParser();
var doc = parser.parseFromString(this.responseText, 'text/html');

然后使用DOM API获取所需的元素:

var nodes = doc.querySelectorAll('a:not([href="../"])');

最后,使用Array.map将节点映射到它们的href属性:

// Can't use nodes.map here because nodes in a NodeList, not an array
var links = Array.prototype.map.call(nodes, function(element)
{
    // Can't use element.href here because we're in a different document
    return element.getAttribute('href');
});

如果你把这些放在一起:

var exampleResponseText = `<html>
<head><title>Index of /browserify-view/build/source/pic/</title></head>
<body bgcolor="white">
<h1>Index of /browserify-view/build/source/pic/</h1><hr><pre><a href="../">../</a>
<a href="wd0c9af04bbf54efc9a2f7ba766a6694f2421b1dc.png">wd0c9af04bbf54efc9a2f7ba766a6694f2421b1dc..&gt;</a> 22-Jul-2016 22:29               65180
<a href="thumb-wd20f381801bb51.png">thumb-wd20f381801bb51.png;</a> 22-Jul-2016 22:33               10779
</pre><hr></body>
</html>`;
var parser = new DOMParser();
var doc = parser.parseFromString(exampleResponseText, 'text/html');
var nodes = doc.querySelectorAll('a:not([href="../"])');
var links = Array.prototype.map.call(nodes, function(element)
{
    return element.getAttribute('href');
});
console.log(links);

你可以做

str.scan(/(?<=<a href=").+?'.png/)

返回一个数组:

["wd0c9af04bbf54efc9a2f7ba766a6694f2421b1dc.png", "thumb-wd20f381801bb51.png"]

分解正则表达式

/(?<=<a href=").+?'.png/
  • (?<=<a href=")是一个正面的后面查找,它匹配主表达式之前的<a href="字符串,但不将其包含在结果中。

  • .+?匹配任意字符1次或1次以上,使用lazy操作符匹配尽可能少的字符。

  • '.png匹配.png