Regular expressions, often referred to as regex or regexp, which is a powerful tool for pattern matching and text manipulation. In python, the ‘re’ module provides the support for using regex and allows developers to perform complex string operations with ease. Whether you are a beginner or a experienced developer, having a cheat sheet in python can be greatly helpful.
Basic Patterns
Literal Characters
Description
abc
Matches the exact string ‘abc’.
Example
import repattern =r'python'text ='Python is a powerful programming language.'match = re.search(pattern, text, re.IGNORECASE)print(match.group())# Output: Python
import repattern =r'\d+'text ='The price of the product is $50.99.'match = re.search(pattern, text)print(match.group())# Output: 50
Quantifiers
Pattern
Description
*
Matches 0 or more occurrences.
+
Matches 1 or more occurrences.
?
Matches 0 or 1 occurrence.
{n}
Matches exactly n occurrences.
{n,}
Matches n or more occurrences.
{n,m}
Matches between n and m occurrences.
Example
import repattern =r'\b\w{3,5}\b'text ='Regex is a powerful tool for text processing.'matches = re.findall(pattern, text)print(matches)# Output: ['Regex', 'tool', 'text']
Anchors
Pattern
Description
^
Matches the start of a string.
$
Matches the end of a string.
Example
import repattern =r'^Python'text ='Python is a popular programming language.'match = re.search(pattern, text)print(match.group())# Output: Python