+91 81900 98289

Python RegEx

This Python RegEx lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

The re module searches text by pattern. \d means a digit. + means one or more. Raw strings, written with an r before the quote, keep backslashes literal.

search returns a match object or None. group() is the text that matched.

Example 1: Start here

Test a pattern on a short sample before you trust it on a full file.

import re # load a tool that comes with Python phone = "Call 8190098289 today" # text found = re.search(r"\d+", phone) # a match, or None when nothing fits print(found.group())

Example 2: Search

\d+ means one or more digits. group returns the matched text.

import re # load a tool that comes with Python print(re.search(r"\d+", "Batch 12").group())

Example 3: Find all

findall returns every match as a list.

import re # load a tool that comes with Python print(re.findall(r"\d+", "Room 3 and room 12"))

Example 4: Replace

sub replaces each match with the new text.

import re # load a tool that comes with Python print(re.sub(r"\d+", "#", "Batch 12"))
Test a pattern on a short sample before you trust it on a full file.
Call Now 81900 98289