how to use regex in python for beginners
How to use regex in Python for beginners
Regex in Python is a way
to search, match, and replace text using patterns instead of exact words. In
Python, you usually work with it through the built-in re module.
Quick Scoop
If you are just starting, think of regex as a
smarter text search tool: you describe the pattern you want, and Python finds
it for you. The most common beginner functions are re.search(),
re.match(), re.findall(), and re.sub().
Basic setup
import re Use raw
strings for patterns, like r"\d+", so backslashes are handled
correctly. The Python documentation recommends learning regex through the
re module with this style.
Main functions
re.search(pattern, text): finds the first match anywhere in the string. [2] re.match(pattern, text): checks only from the start of the string. [2] re.findall(pattern, text): returns all matches as a list. [4][2]
re.sub(pattern, replacement, text): replaces matched text. [4][2]
Simple examples
import re text = "I have
2 apples and 3 bananas" print(re.findall(r"\d+", text)) # ['2', '3']
print(re.search(r"apples", text)) # match object print(re.sub(r"\s", "-",
text)) # I-have-2-apples-and-3-bananas Here, \d+
means “one or more digits,” and \s means whitespace. These
shorthand patterns are among the first things beginners should learn.
Useful pattern ideas
.matches any single character except a newline. [2] *means “zero or more.” [2] +means “one or more.” [2]
^matches the start of a string. [2] $matches the end of a string. [2] [abc]matches one character from a set. [2]
Beginner example
import re email = "hello@example.com" pattern = r"^\w+@\w+\\.\w+$"
if re.fullmatch(pattern, email): print("Valid email") This example checks whether a string looks like a simple email address. It is a good reminder that regex is powerful, but for real validation you may still need more careful rules.
[4][2]Learning path
- Start with literal text matches.
- Learn the common shortcuts like
\d,\w, and\s. - Practice with
search,findall, andsub. - Then move on to anchors, character sets, and grouping. [4][2]
Mini tips
- Use raw strings:
r"pattern". [2] - Test small patterns first. [2]
- Prefer
re.fullmatch()when you want the whole string to match. [2]
Regex becomes much easier once you practice with real text snippets. A good first exercise is to extract all numbers from a sentence, then replace spaces with underscores, then validate a simple username pattern.
[4][2]TL;DR:
Import re, write patterns as raw strings, and start with
search, findall, and sub. The Python
docs and beginner tutorials both emphasize learning the shorthand symbols and
practicing with small examples first.