Regular Expression - Grouping and References
In regular expressions,Grouping(Grouping) allows us to treat multiple characters as a single unit, just like parentheses in mathematics. Grouping has two main purposes:
- Treat multiple characters as a whole: you can apply a quantifier to this whole (e.g.,
*,+,?,{n}) - Capture the matched content: you can later reference or extract this matched content
Basic Syntax
Using parentheses () to create a group:
(表达式)
For example,(ab)+ Can match "ab", "abab", "ababab", etc., but cannot match "a" or "b".
Group types
There are several different types of groups in regular expressions:
1. Capturing Group
The most common form of grouping, which captures the matched content and assigns a number (starting from 1).
Example
(
\d
{
4
}
)
(
\d
{
2
}
)
(
\d
{
2
}
)
# Match date format YYYY
MM
DD
This expression creates 3 groups:
- Group 1: 4-digit year
- Group 2: 2-digit month
- Group 3: 2-digit day
2. Non-capturing Group
Use (?:表达式) syntax, which means group but do not capture.
Example
(
?:
Mr
|
Ms
|
Mrs
)
.
(
\w
)
# Match
"Mr. Smith"
but only captures
"Smith"
3. Named Capturing Group
Assign a name to a group to improve readability (syntax may differ across languages).
Python example:
Example
(
?
P
<
year
\d
{
4
}
)
(
?
P
<
month
\d
{
2
}
)
(
?
P
<
day
\d
{
2
}
)JavaScript example:
Example
(
?<
year
\d
{
4
}
)
(
?<
month
\d
{
2
}
)
(
?<
day
\d
{
2
}
)
Group references
One of the most powerful features of groups is the ability to reference already-matched content inside or outside the regex.
1. Backreference
Reference a preceding group inside the regex, using \数字 Syntax:
Example
(
\w
)
\
1
# Match repeated words, such as
"hello hello"
This pattern matches two identical words separated by a space.
2. Named backreference
For named groups, you can reference them by name:
Example
(
?
P
<
word
\w
)
(
?
P
=
word
)# Python syntax
\k
<
word
# JavaScript syntax
3. Substitution reference
Reference group content in a substitution operation:
Python example:
Example
import
re
text
=
"2023-05-15"
new_text
=
re
.
sub
(
r
'(\d{4})-(\d{2})-(\d{2})'
,
r
'\2/\3/\1'
,
text
)
Result: "05/15/2023"
JavaScript example:
Example
let text
=
"2023-05-15"
;
let newText
=
text.
replace
(
/(\d{4})-(\d{2})-(\d{2})/
,
'$2/$3/$1'
)
;
// Result: "05/15/2023"
Practical Application Examples
Example 1: Match HTML tags
Example
<
(
[
a
z
]
[
a
z0
9
]
)
\b
[
^>
]
*>.
*?
\
1
This pattern can match paired HTML tags (such as ), where:
([a-z][a-z0-9]*)Capture the tag name\1Reference the previously captured tag name to ensure consistency before and after
Example 2: Validate repeated words
Example
\b
(
\w
)
\b\s
\
1
\b
Can find consecutive repeated words in text.
Example 3: Date format conversion
Python code:
Example
import
re
date
=
"2023-12-25"
Convert YYYY-MM-DD to DD/MM/YYYY
new_date
=
re
.
sub
(
r
'(\d{4})-(\d{2})-(\d{2})'
,
r
'\3/\2/\1'
,
date
)
(
new_date
)
Output: 25/12/2023
Advanced applications of groups
1. Conditional matching
Some regex engines support conditional matching based on groups:
Example
(
?
(
1
)
true
pattern
|
false
pattern
)
means: if group 1 has matched, match true-pattern; otherwise match false-pattern.
2. Balanced groups (advanced feature)
Used to match nested structures (such as parentheses), requiring support from a specific regex engine.
Common issues and pitfalls
-
Overuse of grouping: unnecessary grouping affects performance
(a)|(b)(if capture is not needed, you should use (?:a|b))-
Group numbering confusion:
-
Greedy matching problem:
<(.)> # will greedily match up to the last >
should use:
<(.?)> # 非贪婪匹配
Practice challenges
- Write a regex to match repeated email usernames (such as
user@domain.com;user@domain.com) - Convert phone number format, from
(123) 456-7890to123-456-7890 - Extract all attributes from HTML tags (such as
the src and alt attributes)
Summary of key points
| Concept | Syntax | Purpose |
|---|---|---|
| Capture group | (pattern) |
Capture matched content and assign numbers |
| Non-capturing group | (?:pattern) |
Group but do not capture |
| Named group | (?P (Python) |
Assign a name to a group |
| Backreference | \1, \2 etc. |
Reference a previously matched group |
| Named backreference | (?P=name) (Python) |
Reference a group by name |
| Substitution reference | $1, $2 or \1, \2 |
Reference a group in the replacement string |
Mastering the grouping and referencing features of regular expressions allows you to:
- Build more complex matching patterns
- Extract and process specific parts of strings
- Implement intelligent string conversion
- Validate complex text structures