Regular Expressions - 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 quantifiers to this whole (such as
*、+、?、{n}) - Capture matched content: You can reference or extract this portion of matched content later
Basic Syntax
Use parentheses()to create groups:
(expression)
For example,(ab)+can match "ab", "abab", "ababab", etc., but cannot match "a" or "b".
Grouping Types
There are several different types of groups in regular expressions:
1. Capturing Group
The most common form of grouping; it captures the matched content and assigns a number (starting from 1).
Example
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(?:expression)syntax, meaning grouping only without capturing.
Example
3. Named Capturing Group
Assign names to groups to improve readability (syntax may differ between languages).
Python Example:
Example
JavaScript Example:
Example
Group References
One of the most powerful features of groups is the ability to reference matched content inside or outside the regular expression.
1. Backreference
To reference an earlier group inside the regular expression, use\digitsyntax:
Example
This pattern matches two identical words separated by a space.
2. Named Backreference
For named groups, you can reference them by name:
Example
\k<word># JavaScript syntax
3. Replacement Reference
Reference group content in replacement operations:
Python Example:
Example
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 newText = text.replace(/(\d{4})-(\d{2})-(\d{2})/, '$2/$3/$1');
// Result: "05/15/2023"
Practical Application Examples
Example 1: Matching HTML Tags
Example
This pattern can match paired HTML tags (such as<div>...</div>), where:
([a-z][a-z0-9]*)Captures the tag name\1References the previously captured tag name to ensure consistency
Example 2: Detecting Duplicate Words
Example
Can find consecutively repeated words in text.
Example 3: Date Format Conversion
Python Code:
Example
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)
print(new_date) # Output: 25/12/2023
Advanced Applications of Grouping
1. Conditional Matching
Some regex engines support conditional matching based on groups:
Example
Indicates that 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); requires support from specific regex engines.
Common Issues and Pitfalls
Overusing groups: Unnecessary groups can affect performance
- Bad example:
(a)|(b)(If capture is not needed, use(?:a|b))
- Bad example:
Group numbering confusion:
- Group numbers start at 1 in the order of opening parentheses
- Non-capturing groups are not numbered
Greedy matching issues:
<(.*)> # will greedily match up to the last >
You should use:
<(.*?)> # non-greedy matching
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
<img src="..." alt="...">the src and alt within)
Summary of Key Points
| Concept | Syntax | Purpose |
|---|---|---|
| Capturing Group | (pattern) |
Captures matched content and assigns a number |
| Non-capturing Group | (?:pattern) |
Groups without capturing |
| Named Capturing Group | (?P<name>pattern) (Python) |
Assigns a name to the group |
| Backreference | \1, \2wait |
References a previously matched group |
| Named Backreference | (?P=name) (Python) |
References a group by name |
| Replacement Reference | $1, $2or\1, \2 |
References groups in replacement strings |
Mastering grouping and references in 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