4.6 Grouping and Remembering a Sub-Pattern
4.6 Grouping and Remembering a Sub-Pattern
We have seen the use of parentheses to group a subpattern inside a pattern. For example, in the pattern
/\\cite{([^}])+}/
there is one group [^}]. Here, this subpattern is required to be repeated one or more times. In the pattern
/\\cite{([A-Z][a-zA-Z]*(19|20)?\d{2},)*[A-Z][a-zA-Z]*(19|20)?\d{2}}/
there are two parenthesized sub-patterns or groups. These are given below.
([A-Z][a-zA-Z]*(19|20)?\d{2},)
(19|20)
The first can be repeated zero or more times. It is indicated by putting a * behind the closing parentheses. The second is contained in the first and occurs in another place also. In each of the two occurrences of the subpattern, the occurrence is optional. This is achieved by putting a ? after the subpattern.
In these examples, parentheses have been used to group a subpattern so that we treat the subpattern like a single entity and then use a multiplier such as *, +, ?, or {2,5} after it. We have also seen that one subpattern can be inside another.
Using parentheses to group a subpattern does have an additional effect. Perl remembers what part of the target string matches a grouped subpattern. Let us look at some examples to clarify the point.
