Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What does "?:" mean in a Python regular expression?
In Python regular expressions, the ?: syntax creates a non-capturing group. This allows you to group parts of a pattern without storing the matched text for later retrieval.
What are Non-Capturing Groups?
A non-capturing group groups regex tokens together but doesn't create a capture group that you can reference later. The syntax is (?:pattern) where ?: immediately follows the opening parenthesis.
Example
import re
# Non-capturing group
pattern = r'Set(?:Value)'
text = "SetValue"
match = re.search(pattern, text)
if match:
print(f"Full match: {match.group(0)}")
print(f"Number of groups: {len(match.groups())}")
Full match: SetValue Number of groups: 0
Capturing vs Non-Capturing Groups
Let's compare regular capturing groups with non-capturing groups ?
import re
text = "SetValue"
# Capturing group
capturing = r'Set(Value)'
match1 = re.search(capturing, text)
print("Capturing group:")
print(f"Full match: {match1.group(0)}")
print(f"Group 1: {match1.group(1)}")
# Non-capturing group
non_capturing = r'Set(?:Value)'
match2 = re.search(non_capturing, text)
print("\nNon-capturing group:")
print(f"Full match: {match2.group(0)}")
print(f"Number of groups: {len(match2.groups())}")
Capturing group: Full match: SetValue Group 1: Value Non-capturing group: Full match: SetValue Number of groups: 0
Practical Example with Alternation
Non-capturing groups are useful when you need grouping for alternation but don't want to capture the result ?
import re
# Match color followed by any word
pattern = r'(?:red|green|blue) car'
text = "I have a red car and a blue car"
matches = re.findall(pattern, text)
print("Matches found:", matches)
# With capturing groups (for comparison)
pattern_capture = r'(red|green|blue) car'
matches_capture = re.findall(pattern_capture, text)
print("With capturing groups:", matches_capture)
Matches found: ['red car', 'blue car'] With capturing groups: ['red', 'blue']
When to Use Non-Capturing Groups
| Use Case | Example | Benefit |
|---|---|---|
| Alternation without capture | (?:cat|dog) |
Cleaner output |
| Quantifiers on groups | (?:abc)+ |
Better performance |
| Complex patterns | (?:https?://) |
Memory efficiency |
Conclusion
The ?: syntax creates non-capturing groups that group regex tokens without storing matches. Use them when you need grouping for alternation or quantifiers but don't need to access the matched content later.
