
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How regular expression grouping works in Python?
Grouping
We group part of a regular expression by surrounding it with parentheses. This is how we apply operators to the complete group instead of a single character.
Capturing Groups
Parentheses not only group sub-expressions but they also create backreferences. The part of the string matched by the grouped part of the regular expression, is stored in a backreference. With the help of backreferences, we reuse parts of regular expressions.
In practical applications, we often need regular expressions that can match any one of two or more alternatives. Also, we sometimes want a quantifier to apply to several expressions. All of these can be achieved by grouping with parentheses; and, using alternation with the vertical bar (|).
Alternation is useful when we want to match any one of several different alternatives. For example, the regex aircraft|airplane|jet will match any text that contains aircraft or airplane or jet. The same objective can be achieved using the regex air(craft|plane)|jet.
Example
import re s = 'Tahiti $% Tahiti *&^ 34 Atoll' result = re.findall(r'(\w+)', s) print result
Output
This gives the output
['Tahiti', 'Tahiti', '34', 'Atoll']
- Related Articles
- How regular expression back references works in Python?
- Explain C# Grouping Constructs in regular expression
- How regular expression modifiers work in Python?
- How regular expression alternatives work in Python?
- How regular expression anchors work in Python?
- Regular Expression Modifiers in Python
- Regular Expression Patterns in Python
- Regular Expression Examples in Python
- Regular Expression Matching in Python
- How to match parentheses in Python regular expression?
- How does [d+] regular expression work in Python?
- How does B regular expression work in Python?
- How to use wildcard in Python regular expression?
- How to use range in Python regular expression?
- How to use variables in Python regular expression?
