Python Regex Cheat Sheet

In this article we want to learn about Python Regex Cheat Sheet, so Python regex or regular expression is a powerful tool that you can use for searching, matching and manipulate strings. it can be used for different tasks including web scraping, natural language processing and data cleaning. also regex syntax can be confusing and difficult to remember. that is why it is good to have a cheat sheet.

 

In this article we want to provide you with a Python regex cheat sheet that you can use as  reference when working on your projects.

 

 

Python Regex Basic Syntax

. Matches any character except a newline.
^ Matches the start of a string.
$ Matches the end of a string.
[] Matches any one of the characters inside the brackets.
[^] Matches any character that is not inside the brackets.
| Matches either the expression before or after the pipe.
() Groups expressions together.

 

 

 

Python Regex Quantifiers

* Matches 0 or more occurrences of the previous expression.
+ Matches 1 or more occurrences of the previous expression.
? Matches 0 or 1 occurrence of the previous expression.
{n} Matches exactly n occurrences of the previous expression.
{n,} Matches n or more occurrences of the previous expression.
{n,m} Matches between n and m occurrences of the previous expression.

 

 

 

Python Regex Anchors

\b Matches word boundary.
\B Matches non-word boundary.
\A Matches start of a string.
\Z Matches end of a string.

 

 

 

These are a few examples that how you can use these regex patterns in Python:

re.findall(r’\d+’, ‘I have 2 apples and 3 oranges’) This code will return a list and it contains the numbers 2 and 3.
re.sub(r’\s+’, ‘_’, ‘Hello world’) This code will replace all whitespace characters with an underscore, resulting in the string “Hello_world”.
re.search(r’\b\w{5}\b’, ‘The quick brown fox jumps over the lazy dog’) This code will search for a five letter word in the given string and return the first match, which is “quick”.

 

 

So we can say that Python regex is powerful tool that can help you manipulate and extract data from strings. by using this cheat sheet you can quickly reference the most commonly used regex patterns and syntax.

 

Subscribe and Get Free Video Courses & Articles in your Email

 

Leave a Comment

Share via
Copy link
Powered by Social Snap
×