-- Start
In
Brackets and backward referencesThe section describes two uses of parentheses: grouping and capturing.
Group
In fact, the regular expression also provides three types of structures for grouping:
Metacharacter) |
Match (matches) |
(...) |
Group |
(? :...) |
Group |
(?> ...) |
Curing Group |
What are the differences between them? Let's take a look at an example.
#! /Usr/bin/perlmy $ testtext = "# test #"; # test text # benchmark if ($ testtext = ~ M/#. * #/) {print "#. * # matched # test # \ n" ;}# test (...) if ($ testtext = ~ M/(#. * #)/) {print "(#. * #) matches $1 \ n" ;}# test (? :...) If ($ testtext = ~ M /(? : #. * #)/) {Print "(? : #. * #) Matched $1 \ n ";}# test (?> ...) If ($ testtext = ~ M/(?> #. * #>)/) {Print "(?> #. * #>) Matches $1 \ n ";} else {print" (?> #. * #>) Cannot match # test # \ n ";}
Running result:
#. * # Matched # test # (#. * #) matched # test #(? : #. * #) Matched (?> #. * #>) Unmatched # test #
We can see from the results that ,(? :...) Can only be used for grouping, and (...) in addition to grouping, the content in brackets is captured. So (?> ...) What does that mean? (?> #. * #>) Why cannot I match # test? To understand what a solid group is, We must go deep into the matching principle of regular expressions.The difference between greedy, non-greedy, and placeholderThis section describes what a placeholder is. If you understand what a placeholder is, you must know why.
(?> #. * #>) Cannot match # test #.
Capture and Back Reference
We know that parentheses can be used in addition to grouping and capturing. Why should we capture the content in parentheses? The main reason is that after the capture, we can get the previously captured content through backward reference, which is very important in the text replacement operation. The format of capture and subsequent reference is as follows:
Metacharacter) |
Match (matches) |
(...) |
Capture |
\ N |
Reference the Matching content in the nth Bracket |
(? <Name> ...) |
Name capture |
Naming and capturing means to give a name to the captured content. Later we can use this name to reference its content, instead of using \ n. Perl and Java do not support naming and capturing.
--For more information, see:Regular Expressions
--Shengming: reprinted, please indicate the source
-- Last updated on 2012-05-13
-- Written by shangbo on 2012-05-13
-- End