How to control the overal mode of a regular expression.
Groups
This page describes how to group tokens together for use in repetitions, references or alternatives.
Character
Description
Example
Ways to define groups
(expn-text)
Where "expn-text" can be any regular expression
Begins a group of general tokens (includes metatokens).
Although the expression inside the group can be manipulated externally as a single token (for the purpose of repetition and alternatives) the group still matches the number of tokens it contains.
Options may be used on the group which cause it to be declared as a metatoken, such that it's contents must match, but do not form part of the match text. For more information see Special Groups.
Options may be used to define conditional groups, such that different tests can be performed base don the outcome of previous tests. For more information see Special Groups.
If the group makes a match and it has not been declared a metatoken, then the match text for the group can be used as a group reference in the same search, or replacement text in a replacement operation.
Groups may be used to define the scope of modes described in Modes.
(abc){3}
matches
abcabcabc
.
(?:expn-text)
Options described on the page Modes defined within a group normally apply at the beginning of the group, to the remainder of the regular expression by reading order. This type of group overrides that behavior ensuring that the mode change applies to the local group only.
(?:(?i)abc){3}
matches
abcabcabc
or
ABCABCABC
.
\0
This token is not useful for search, but can be beneficial for replace. It represents the root group, whose bracket delimiters do not actually appear in the search expression. Clearly, the result of whole regular expression, is an invalid value until a whole match has been made. When this token is used in a replacement expression, the whole match will be replaced into the original search text.
\n
Where n is the reading order index of a group
This token may either be used in search or replace operations. The index of the group can be established by counting groups by reading order in the search expression. It is not useful to reference group 5 in group 2, since by definition, there are no search results for group 5 when still attempting a match in group 2. Care must be taken when using alternative groups, since some of the alternative group results will remain undefined even when a complete match is made.
(abc|def)=\1
matches
abc=abc
or
def=def
, but not
abc=def
or
def=abc
.
Ways to define alternatives
|
"pipe"
The pipe is not a token, but it serves to separate alternative groups of tokens in a similar manner to groups. Unlike groups the pipe specifies that the tokens either side are alternatives. The way in which the pipe operates ensures that pipes may be chained in runs.
abc|def|xyz
matches
abc
,
def
or
xyz
|
"pipe"
When used with groups, alternatives may be factored.