Regular Expressions in Python
Regular expressions (regex) are used to search, match, and manipulate text patterns in Python. The re module provides all necessary functions.
re module
| Function | Description |
|---|---|
re.match(pattern, string) | Checks for a match at the beginning of the string |
re.search(pattern, string) | Searches for a match anywhere in the string |
re.findall(pattern, string) | Returns a list of all matches |
re.split(pattern, string) | Splits string by occurrences of the pattern |
re.sub(pattern, repl, string) | Replaces matches with repl |
re.compile(pattern) | Compiles a regex pattern for reuse |
| Symbol | Meaning |
|---|---|
. | Any character except newline |
^ | Start of string |
$ | End of string |
* | 0 or more repetitions |
+ | 1 or more repetitions |
? | 0 or 1 repetition (optional) |
{n} | Exactly 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 | Digit (0-9) |
\D | Non-digit |
\s | Whitespace (space, tab, newline) |
\S | Non-whitespace |
\w | Word character (letters, digits, underscore) |
\W | Non-word character |
Match at beginning:
Search anywhere:
Find all matches:
Split string:
Substitute text:
Using compiled patterns:
Regex allows powerful text pattern matching.
Use raw strings (r"pattern") to avoid escaping backslashes.
re module functions return match objects or lists.
Can be combined with loops, conditionals, and comprehensions.
Useful for validation, parsing, and text cleaning
Take quizzes related to this topic and see where you stand!
Start Quiz Now