匹配对标签与正则表达式 [英] Matching pair tag with regex

查看:169
本文介绍了匹配对标签与正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从xhtml文档中检索具有其内容的特定标签,但是它匹配了错误的结束标签.

I'm trying to retrieve specific tags with their content out of an xhtml document, but it's matching the wrong ending tags.

在以下内容中:

<cache_namespace name="content">
    <content_block id="15">
    some content here

        <cache_namespace name="user">
            <content_block id="welcome">
            Welcome Apikot!
            </content_block>
        </cache_namespace>
    </content_block>
</cache_namespace>

id ="welcome"的content_block结束标记实际上与第一个打开的content_block标记的结束标记匹配.

The content_block ending tag for id="welcome" actually get's matched as the ending tag of the first opening content_block tag.

我正在使用的正则表达式是:

The regex I'm using is:

/<content_block id="(.*)">([\w\W]*?)<\/content_block>/i

是否有关于我失败的地方的指针?

Any pointers as to where I'm failing?

推荐答案

...,答案始终相同:无法完成HTML +正则表达式.对不起.为您的特定框架使用HTML解析库.或者,如果保证您的文档仅包含有效的XHTML,请采用抖动中注释所建议的XPath方法.

… and the answer is always the same: HTML + regex cannot be done. Sorry. Use an HTML parsing library for your particular framework. Or, if your document is guaranteed to only contain valid XHTML, take the XPath approach as proposed by jitter in a comment.

这篇关于匹配对标签与正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆