DEV Community

Volodyslav
Volodyslav

Posted on

1 1 1 1 1

Python RegEx Cheat Sheet

Hello! This cheat sheet for you! Enjoy!

Regular expressions in Python are handled using the re module. Firstly you have to import re module by writing import re in the first line of your python file.

Regex Patterns:

.: Any character except a newline.
^: Start of the string.
$: End of the string.
*: Zero or more repetitions.
+: One or more repetitions.
?: Zero or one repetition.
{n}: Exactly n repetitions.
{n,}: At least n repetitions.
{n,m}: Between n and m repetitions.
[abc]: Matches a, b, or c.
[^abc]: Matches any character except a, b, or c.
\d: Matches any digit.
\D: Matches any non-digit.
\w: Matches any word character (alphanumeric plus underscore).
\W: Matches any non-word character.
\s: Matches any whitespace character.
\S: Matches any non-whitespace character.

Basic functions:

re.search(): Scans through a string, looking for any location where the regex pattern matches.
re.match(): Checks for a match only at the beginning of the string.
re.findall(): Finds all substrings where the regex pattern matches and returns them as a list.
re.finditer(): Finds all substrings where the regex pattern matches and returns them as an iterator of match objects.
re.sub(): Replaces the matches with a specified string.

Examples

print(re.search(r"\d+", "Python is cool! 100 % ! ").group())  # 100
print(re.match(r"\w+", "Hello world").group())  # Hello
print(re.findall(r"\d+", "My 1 Python and my 2 JavaScript"))  # ['1', '2']
print(re.sub(r"\d+", "very", "Python is 1 cool and 2 nice."))  # Python is very cool and very nice.

Enter fullscreen mode Exit fullscreen mode

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more