Groups
Expressions | Explanations |
---|---|
( ) |
Matches the expression inside the parentheses and groups it which we can capture as required |
(?#…) |
Read a comment |
(?PAB) |
Matches the expression AB, which can be retrieved with the group name. |
(?:A) |
Matches the expression as represented by A, but cannot be retrieved afterwards. |
(?P=group) |
Matches the expression matched by an earlier group named “group” |
Examples:
Python3
import re example = (re.search(r "(?:AB)" , "ACABC" )) print (example) print (example.groups()) result = re.search(r "(\w*), (\w*)" , "geeks, best" ) print (result.groups()) |
Output:
<re.Match object; span=(2, 4), match='AB'>
()
('geeks', 'best')
Explanation:
In the first example, (?:AB) will search and matches the expression AB and will print out the match and its position. Since ACABC contains AB, it will print the match(‘AB’) and its position(2,4) but as stated, this cannot be retrieved afterward. So, if we try to print the group of the output, it will show an empty bracket.
In the second example, we have captured two groups, one group which has 0 or more alphanumeric characters followed by comma and space and then followed by another group which has again 0 or more alphanumeric characters. In geeks, best geeks and best are captured as the first and second groups. So, when we print out these groups we will have (‘geeks’, ‘best) as the groups captured.
Regex Cheat Sheet – Python
Regex or Regular Expressions are an important part of Python Programming or any other Programming Language. It is used for searching and even replacing the specified text pattern. In the regular expression, a set of characters together form the search pattern. It is also known as the reg-ex pattern. The tough thing about Regex is not learning or understanding it but remembering syntax and how to form patterns according to our requirements.
So, here we have provided a Regex Cheat Sheet containing all the different character classes, special characters, modifiers, sets, etc. which are used in the regular expression.
Table of Content
- Basic Characters
- Quantifiers
- Character Classes
- Sets
- Groups
- Assertions
- Flags