This article mainly introduces Regular expressionsBacktracking of learning tutorialsReferencebackreference, combined with examples, a detailed analysis of the concept, function and implementation skills of backreference, friends in need You can refer to the following example
This article describes the regular expression backreference backreference. Share it with everyone for your reference, the details are as follows:
In all examples, the regular expression matching results are included between [and] in the source text. Some examples will be implemented using Java. If It is the usage of regular expressions in Java itself, which will be explained in the corresponding place. All java examples are tested under JDK1.6.0_13.
1. Problem introduction
A problem of matching title tags (H1-H6) in HTML pages:
Text:
<body> <h1>Welcome to my page</H1> Content is pided into twosections:<br> <h2>Introduction</h2> Information about me. <H2>Hobby</H2> Information about my hobby. <h2>This is invalid HTML</h3> </body>
Regular expression: <[hH][1-6]>.*?[hH][1-6]>
Result:
Analysis: Pattern<[hH][1 -6]> matches the opening tag of any first-level title, and is not case-sensitive. In this example, it matches
2. Backreference matching
Backreference means that the second half of the pattern refers to the subexpression defined in the first half. As for the use, division and reference of subexpressions, they have been introduced before. Now let’s solve the previous example:
Text:
<body> <h1>Welcome to my page</H1> Content is pided into twosections:<br> <h2>Introduction</h2> Information about me. <H2>Hobby</H2> Information about my hobby. <h2>This is invalid HTML</h3> </body>
Regular expression: <[hH]([1-6])>.*?[ hH]\1>
Result:
##
【
PS: Here are two very convenient regular expression tools for your reference:
JavaScriptRegular expression online testing tool:
http://tools.jb51.net/regex/javascript
Regular expression Expression online generation tool:
http://tools.jb51.net/regex/create_reg
The above is the detailed content of Detailed explanation of backreference of regular expressions_regular expressions. For more information, please follow other related articles on the PHP Chinese website!