Python Regex Cheat Sheet - GeeksforGeeks

24 Jan, 2021
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 reg-ex pattern. Tough thing about Regex is not learning or understanding it but remembering syntax and how to form pattern 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 regular expression.
Explanations
Example:
Python3
import re  print(re.search(r"^x","xenon"))print(re.search(r"s$","geeks"))
Output:
<re.Match object; span=(0, 1), match='x'>
<re.Match object; span=(4, 5), match='s'>
Explanation:
First import the regex module with the command import re
Then, in the first example, we are searching for “^x” in the word “xenon” using regex. ^ this character matches the expression to its right, at the start of a string. So, ^x will search for character x in the beginning of the string. Since xenon starts with x, it will find the match and will return the match(‘x’) and its position(0,1)
Similarly, in the second example s$ will search for the character s at the end of the string, now since geeks end with s, so it will find the match and will return the match(‘s’) and its position(4,5).
Their default searching method is Greedy. But if ? is added to qualifiers (+, *, and ? itself) it will perform matches in a non-greedy manner.
Examples:
Python3
import re  print(re.search(r"9+","289908"))print(re.search(r"\d{3}","hello1234"))
Output:
<re.Match object; span=(2, 4), match='99'>
<re.Match object; span=(5, 8), match='123'>
Explanation:
In the first example, 9+ will search for the number 9 one or more times. Since 289908 contains 9 two times, the regex will match it and will print the match(’99’) and its position(2,4)
In the second example, \d{3} will search for digits exactly 3 times. Since hello1234 have digits, it will match exactly 3 digits which will be encountered first that are 123 and not 4, because {3} will match for exactly 3 digits. So it will print the match(‘123’) and its position(5,8)
Examples:
Python3
import re  print(re.search(r"\s","xenon is a gas"))print(re.search(r"\D+\d*","123geeks123"))
Output:
<re.Match object; span=(5, 6), match=' '>
<re.Match object; span=(3, 11), match='geeks123'>
Explanation:
In the first example, \s will search for the blank space and whenever it encounters the first blank space it will print out that match. Since xenon is a gas that contains blank spaces, it will encounter the first blank space and print out that match(‘ ‘) and its position(5,6)
In the second example, \D+\d* will search for one or more non-digits characters followed by 0 or more digits. In our case, geeks123 best fits the description as it contains 1 or more non-digits characters(geeks) followed by 0 or more digit characters(123). So it will print the match(‘geeks123’) and its position(3,11).
Examples:
Python3
import re  print(re.search(r"[^abc]","abcde"))print(re.search(r"[a-p]","xenon"))
Output:
<re.Match object; span=(3, 4), match='d'>
<re.Match object; span=(1, 2), match='e'>
Explanation:
In the first example, [^abc] will search for anything except a, b and c, so regex will match the first character which is not a or b or c and will print out that match. Since abcde contains d as its first match that is neither a nor b nor c, it will print out that match. So match would be (‘d’) and its position would be (3,4)
In the second example, [a-p] will search for the character between a to p. In xenon the first word between a-p is e it will print out that search. So match would be (‘e’) and its position would be (1,2)
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. 
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)
Examples:
Python3
import re  exp = """hello thereI am fromGeeks 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)
python-regex
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()