Flags
Expression | Explanation |
---|---|
a |
Matches ASCII only |
i |
Ignore case |
L |
Locale character classes |
m |
^ and $ match start and end of the line (Multi-line) |
s |
Matches everything including newline as well |
u |
Matches Unicode character classes |
x |
Allow spaces and comments (Verbose) |
Examples:
Python3
import re exp = """hello there I am from Geeks for Geeks""" print (re.search(r "and" , "Sun And Moon" , flags = re.IGNORECASE)) print (re.findall(r "^\w" , exp, flags = re.MULTILINE)) |
Output:
<re.Match object; span=(4, 7), match='And'>
['h', 'I', 'G']
Explanation:
In the first example, the IGNORECASE flag will search for the word and irrespective of its case (whether uppercase or lowercase), So it ignores the case and matches And in the expression. So it will print the match(‘And’) and its position(4,7)
In the second example, the MULTILINE flag will search in each and every line and will match when the line is starting an alphanumeric character. Since in Multi-line hello there I am from Geeks for Geeks, every line is starting with an alphanumeric character, so it will match every line and will print the match in an array ([‘h’, ‘I’, ‘G’]).
Note: In MULTILINE flag, we have to use re.findall, since it has many matches (for every line)
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