Skip to content

Regular Expressions

Python regular expressions (regex) are compact pattern descriptions written in a special mini-language that let you search, match, extract, and transform substrings in text. In Python the built-in re module provides functions to compile and apply these patterns, supporting character classes, quantifiers, grouping, and lookaround assertions for powerful text processing.

Module

import re
import re
txt = "Python is a programming language"
x = re.search("^Python.*language$", txt)
if x is not None:
    print("Match Found")
else:
    print("Match not found")
Match Found

findall()

import re

txt = "Python is a programming language"
x = re.findall("i", txt)
print(x)
['i', 'i']

split()

import re

txt = "Python is a programming language"
x = re.split(r"\s", txt)
print(x)
['Python', 'is', 'a', 'programming', 'language']

sub()

import re

txt = "Python is a programming language"
x = re.sub(r"\s", "X", txt)
print(x)
PythonXisXaXprogrammingXlanguage

Match Object

import re

txt = "Python is #1 programming language"
x = re.search(r"\D+", txt)
if x is not None:
    print(x.group())
else:
    print("No match found")
Python is #