Regular Expressions in Python
📘 Python
👁 52 views
📅 Nov 05, 2025
⏱ Estimated reading time: 2 min
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.
1. Importing the re module
2. Basic Regex Functions
| 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 |
3. Regex Patterns
| 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 |
4. Examples
Match at beginning:
Search anywhere:
Find all matches:
Split string:
Substitute text:
Using compiled patterns:
5. Key Points
-
Regex allows powerful text pattern matching.
-
Use raw strings (
r"pattern") to avoid escaping backslashes. -
remodule functions return match objects or lists. -
Can be combined with loops, conditionals, and comprehensions.
-
Useful for validation, parsing, and text cleaning
🔒 Some advanced sections are available for Registered Members
Register Now
Register Now
Share this Post
← Back to Tutorials