Assertions
Expression | Explanation |
---|---|
A(?=B) |
This matches the expression A only if it is followed by B. (Positive look ahead assertion) |
A(?!B) |
This matches the expression A only if it is not followed by B. (Negative look ahead assertion) |
(?<=B)A |
This matches the expression A only if B is immediate to its left. (Positive look behind assertion) |
(?<!B)A |
This matches the expression A only if B is not immediately to its left. (Negative look behind assertion) |
(?()|) |
If else conditional |
Examples:
Python3
import re print (re.search(r "z(?=a)" , "pizza" )) print (re.search(r "z(?!a)" , "pizza" )) |
Output:
<re.Match object; span=(3, 4), match='z'>
<re.Match object; span=(2, 3), match='z'>
Explanation:
In the first example, z(?=a) will search for the character z which is followed by the character a. Since in pizza, we have a character z which is immediately followed by the character a (pizza), so there will be a match. Regex will print the match(‘z’) which is followed by a with its position(3,4)
In the second example, z(?!a) will search for the character z which is not followed by the character a. Since in pizza, we have a character z which is not followed by a but followed by z (pizza), so there will be a match. Regex will print the match(‘z’) not followed by a with its position (2,3)
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