Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
590 views
in Technique[技术] by (71.8m points)

html parsing - Matching pair tag with regex

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

In the following content:

<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>

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="(.*)">([wW]*?)</content_block>/i

Any pointers as to where I'm failing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

… 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...