PS: In all examples, regular expression matching results are included between [and] in the source text. In some examples, java is used. If the regular expression is used in java, it will be described in the corresponding area. All java examples have passed the test under JDK1.6.0 _ 13.
I. Problem Introduction
A question about matching title tags (H1-H6) on an HTML page:
Text:
<Body>
<H1> Welcome to my page </H1>
Content is divided into twosections: <br>
<H2> Introduction
Information about me.
<H2> holobby </H2>
Information about my holobby.
<H2> This is invalid HTML
</Body>
Regular Expression: <[hH] [1-6]> .*? </[HH] [1-6]>
Result:
<Body>
[<H1> Welcome to my page </H1>]
Content is divided into twosections: <br>
[<H2> Introduction
Information about me.
[<H2> holobby </H2>]
Information about my holobby.
[<H2> This is invalid HTML
</Body>
Analysis: the mode <[hH] [1-6]> matches the start tag of any level-1 title and is case insensitive, in this example, it matches
Ii. backtracking and reference matching
Backend Reference refers to the subexpression defined in the first half of a pattern. As for the usage, division, and reference of subexpressions, we have already introduced them in the previous article. Here we will solve the preceding example:
Text: www.2cto.com
<Body>
<H1> Welcome to my page </H1>
Content is divided into twosections: <br>
<H2> Introduction
Information about me.
<H2> holobby </H2>
Information about my holobby.
<H2> This is invalid HTML
</Body>
Regular Expression: <[hH] ([1-6])> .*? </[HH] \ 1>
Result:
<Body>
[<H1> Welcome to my page </H1>]
Content is divided into twosections: <br>
[<H2> Introduction
Information about me.
[<H2> holobby </H2>]
Information about my holobby.
<H2> This is invalid HTML
Analysis: first, match the start title label mode <[hH] ([1-6])>, and use [1-6] As a subexpression using parentheses, the tag mode of the matched ending title is </[hH] \ 1>, where \ 1 indicates referencing the first subexpression ([1-6]), if ([1-6]) matches 1, \ 1 also matches 1. If it matches 2, \ 1 matches 2, therefore, the last invalid title tag will not be matched.