使用正则表达式从 HTML 中提取文本和链接

发布于 2024-08-17 02:40:29 字数 578 浏览 5 评论 0原文

我想从 html 文档中提取文本,并将链接保留在其中。例如:

从这个 HTML 代码中

<div class="CssClass21">bla1 bla1 bla1 <a href="http://www.ibrii.com">go to ibrii</a> bla2 bla2 bla2 <img src="http://www.contoso.com/hello.jpg"> <span class="cssClass34">hello hello</span>

,我想提取这个

bla1 bla1 bla1 <a href="http://www.ibrii.com">go to ibrii</a> bla2 bla2 bla2 hello hello

在 StackOverflow 上的另一篇文章中,我找到了 RegEx <[^>]*> ,它允许通过替换每个匹配来提取文本什么也没有。如何从匹配中排除锚标记?看来正则表达式不允许反向匹配。

I would like to extract text from an html document keeping the links inside it. for example:

From this HTML code

<div class="CssClass21">bla1 bla1 bla1 <a href="http://www.ibrii.com">go to ibrii</a> bla2 bla2 bla2 <img src="http://www.contoso.com/hello.jpg"> <span class="cssClass34">hello hello</span>

I would like to extract just this

bla1 bla1 bla1 <a href="http://www.ibrii.com">go to ibrii</a> bla2 bla2 bla2 hello hello

In another post on StackOverflow i have found the RegEx <[^>]*> which allows to extract text by replacing every match with nothing. How can I exclude the anchor tags from the match? It seems that RegEx do not allow inverse matching.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

零時差 2024-08-24 02:40:30

暂时将 ... 编码为其他内容,删除所有其他标签,然后恢复 标签:

// Example in javascript:
string.
    replace(/<a(.*?)>/g,'\0$1\0').
    replace(/<\/a>/,'\1').
    replace(/<[^>]*>/,'').
    replace(/\0(.*?)\0/,'<a$1>').
    replace(/\1/,'</a>');

在上面的代码中,我使用 NUL 和 SOH 字符(ASCII 0x00 和 0x01)作为 标记的替换,只是因为它们不太可能出现在字符串中。请随意将它们替换为不会出现在字符串中的任何其他字符或字符序列。

从其他评论来看,您似乎正在浏览器中操作。在这种情况下,浏览器已经为您将 HTML 解析为漂亮的 DOM 树。使用 DOM 方法解析树并按照您想要的方式处理它:

function simpleHTML (domNode) {
    var ret = "";
    if (domNode.nodeType === Node.ELEMENT_NODE) {
        var children = domNode.childNodes;
        for (var i=0;i<children.length;i++) {
            var child = children[i];

            // Filter out unwanted nodes to speed up processing.
            // For example, you can ignore 'SCRIPT' nodes etc.
            if (child.nodeName != 'SCRIPT') {
                if (child.nodeName == 'A') {
                    ret += '<a href="' + child.href + '">' +
                               simpleHTML(child) +
                           '</a>';
                }
                else {
                    ret += simpleHTML(child);
                }
            }
        }
    }
    else if (domNode.nodeType === Node.TEXT_NODE) {
        ret +=  domNode.nodeValue;
    }
    return ret;
}
// serialize the whole document:
var simpleDocument = simpleHTML(document.body);

// serialize a div:
var simpleDiv = simpleHTML(document.getElementById('some_div'));

// filter a html formatted string:
var temp = document.createElement('DIV');
temp.innerHTML = original_string;
simple_string = simpleHTML(temp);

Temporarily encode <a href ...>...</a> into something else, remove all other tags then restore the <a> tags:

// Example in javascript:
string.
    replace(/<a(.*?)>/g,'\0$1\0').
    replace(/<\/a>/,'\1').
    replace(/<[^>]*>/,'').
    replace(/\0(.*?)\0/,'<a$1>').
    replace(/\1/,'</a>');

In the code above I use the NUL and SOH characters (ASCII 0x00 and 0x01) as replacements for <a> tags simply because it is highly unlikely that they would appear in strings. Feel free to replace them with any other character or sequence of characters that would not appear in your string.

From additional comments it appears you're operating in a browser. In which case the browser has already parsed the HTML for you into a nice DOM tree. Use DOM methods to parse through the tree and process it the way you want:

function simpleHTML (domNode) {
    var ret = "";
    if (domNode.nodeType === Node.ELEMENT_NODE) {
        var children = domNode.childNodes;
        for (var i=0;i<children.length;i++) {
            var child = children[i];

            // Filter out unwanted nodes to speed up processing.
            // For example, you can ignore 'SCRIPT' nodes etc.
            if (child.nodeName != 'SCRIPT') {
                if (child.nodeName == 'A') {
                    ret += '<a href="' + child.href + '">' +
                               simpleHTML(child) +
                           '</a>';
                }
                else {
                    ret += simpleHTML(child);
                }
            }
        }
    }
    else if (domNode.nodeType === Node.TEXT_NODE) {
        ret +=  domNode.nodeValue;
    }
    return ret;
}
// serialize the whole document:
var simpleDocument = simpleHTML(document.body);

// serialize a div:
var simpleDiv = simpleHTML(document.getElementById('some_div'));

// filter a html formatted string:
var temp = document.createElement('DIV');
temp.innerHTML = original_string;
simple_string = simpleHTML(temp);
森林散布 2024-08-24 02:40:29

正则表达式确实允许通过 lookahead 进行非平凡的否定形式,但在这种情况下作为一个练习是很好的,因为虽然我不是每次 regexp 与 HTML 一起提及时都会热血沸腾的狂热分子,但这确实是一个需要用解析器解决的问题。

Regular expressions do allow a non-trivial form of negation through lookahead but in this case it would be just good as an excercise because, while I'n no zealot that burns with holy fire every time regexp get mentioned together with HTML, this is really a problem to be solved with a parser.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文