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

import re

2. Basic Regex Functions

FunctionDescription
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

SymbolMeaning
.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
\dDigit (0-9)
\DNon-digit
\sWhitespace (space, tab, newline)
\SNon-whitespace
\wWord character (letters, digits, underscore)
\WNon-word character

4. Examples

Match at beginning:

import re text = "Python123" result = re.match(r"Python", text) print(result.group()) # Python

Search anywhere:

result = re.search(r"\d+", text) print(result.group()) # 123

Find all matches:

text = "abc 123 def 456" numbers = re.findall(r"\d+", text) print(numbers) # ['123', '456']

Split string:

text = "apple,banana,orange" fruits = re.split(r",", text) print(fruits) # ['apple', 'banana', 'orange']

Substitute text:

text = "Hello 123 World 456" new_text = re.sub(r"\d+", "#", text) print(new_text) # Hello # World #

Using compiled patterns:

pattern = re.compile(r"\d+") result = pattern.findall("Numbers: 10, 20, 30") print(result) # ['10', '20', '30']

5. Key Points

  • 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


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes