Python Regular Expressions

Python’s re module allows you to search, match, split, and replace text using Regular Expressions (RegEx). It’s powerful for pattern-matching tasks like validating emails, extracting substrings, or replacing text. Below are clear examples with code snippets to help you practice.

RegEx Metacharacters

In Python, regex metacharacters are special symbols that define search patterns, making regular expressions powerful for string matching and manipulation.

RegEx Metacharacters in Python

RegEx Metacharacters in Python Table

RegEx Sets

A set in regex is a collection of characters enclosed within square brackets [], where each character represents a possible match.

RegEx Sets in Python

Basics of Python RegEx

  • Import module: import re
  • Common functions:
    • re.match() → Checks for a match at the beginning of a string.
    • re.search() → Searches for a match anywhere in the string.
    • re.findall() → Returns all matches as a list.
    • re.split() → Splits string by pattern.
    • re.sub() → Replaces matches with new text.

RegEx Examples

Let us see some Regular Expression examples in Python:

1. Match at Start using the match() function

Check for a match at the beginning of a string using the match() function:

# Match at start of a string in Python RegExp using match()

import re

pattern = "^c" # ^ metacharacter is for start of string
txt = "cricket"

# The match() checks for a regular expression match only at the very beginning of the string
res = re.match(pattern, txt)
if res:
    print("Search is successful")
else:
    print("Search is not successful")

Output

Search is successful

2. Match at the end of a string

Check for a match at the end of a string using the search() function.

# Match at end of a string in Python RegExp

import re

pattern = "worldcup$" # $ metacharacter is for end of string
txt = "cricket worldcup"

# The search() will scan the whole string for a match
res = re.search(pattern, txt)
if res:
    print("Search is successful")
else:
    print("Search is not successful")

Output
Search is successful

3. Search Anywhere using the search() function

Search for a match anywhere in the string using the search() method:

# Search anywhere using the search() function in Python RegExp
# Find a string that starts with "The", has anything in between, and then contains "Cup"

import re

txt1 = "The Cricket World Cup"
res = re.search("^The.*Cup", txt1)

if res:
    print("Search is sucessful")
else:
    print("Search is not sucessful")

txt2 = "The11Cup"
res2 = re.search("^The.*Cup", txt2)

if res2:
    print("Search is successful")
else:
    print("Search is not successful")

Output

Search is successful
Search is successful

4. Find All Matches using the findall() function

To find and return all matches as a list, use the findall() function in Python:

# Find all matches using the findall() function in Python Regex
# Find all occurrences of "sun" or "fun" in the text

import re

txt = "sun fun run sam fan"

# [sf] -> Match either s or f at this position
# un -> Followed immediately by "un"
matches = re.findall("[sf]un", txt)

print(matches)

Output

['sun', 'fun']

5. Search for vowels in a list with Python Regex findall()

To search for vowels, use the findall() function in Python.

# Search for vowels in a list with Python Regex findall()
import re

words = ["apple", "banana", "sky", "cricket"]
pattern ="[aeiou]"

# findall() returns all matches in a string
for w in words:
    vowels = re.findall(pattern, w)
    print(f"{w}:{vowels}")

Output

apple:['a', 'e']
banana:['a', 'a', 'a']
sky:[]
cricket:['i', 'e']

6. Split a string at each whitespace character with Python Regex split()

To split a string, use the split() function in Python.

# Split a string at each whitespace character with Python Regex split()

import re

txt = "World Wide Web"

# We can also use re.split("\\s", txt)
res = re.split(r"\s", txt)

print(res)

Output

['World', 'Wide', 'Web']

7. Replace a text using the sub() function in Python Regex

To replace matches with new text, use the sub() function in Python:

import re
txt = "T20 World Cup"
res = re.sub(r"T20", "ODI", txt)
print(res)

Output

ODI World Cup

We replaced T20 with ODI in the above example.

8. Replace part of a string that matches a regex pattern using the sub() function

To replace a part of a string that matches a pattern, use the sub() function:

# Replace part of a string that matches a regex pattern using the sub() function in Python Regex

import re

txt = "cricket worldcup"

res = re.sub("[aeiou]", "*", txt)
print(res)

Output

cr*ck*t w*rldc*p

If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others.


For Videos, Join Our YouTube Channel: Join Now


Read More:

Python Encapsulation
Python Exception Handling
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment