Python RegEx Programs with Solutions

Python Practice › RegEx Programs

Python RegEx Programs with Solutions

20 programs19 easy1 medium0 hard

20 regular expression programs: validating emails, phone numbers, PIN codes and passwords, extracting numbers, dates, hashtags and URLs, and cleaning or reformatting text with re.sub.

Before you start

Read the RegEx lesson first if the topic is new to you.

All programs

Create a table

Create a table

EasySQLite Programs · 1 of 20

Write a Python program to create a SQLite table and list the tables in the database.

Output
[('students',)]

Approach

  1. CREATE TABLE, then query sqlite_master.

Solution

Python
import sqlite3 conn = sqlite3.connect(":memory:")conn.execute("CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT NOT NULL, marks INTEGER)")print(conn.execute("SELECT name FROM sqlite_master WHERE type = 'table'").fetchall())
Output
[('students',)]

Line by line

Line 3

:memory: creates a temporary database that disappears when the program ends.

Learn the concept

New to this topic? Read the lesson, then come back.

More sqlite programs

← All 20 SQLite Programs

Match positions with finditer

Python Practice › RegEx Programs › Program 19

Match positions with finditer

EasyRegEx Programs · 19 of 20

Write a Python program to print each match of a word with its start and end positions.

Output
python (0, 6)
pytest (11, 17)
pyodide (22, 29)

Approach

  1. finditer gives match objects with span().

Solution

Python
import re for m in re.finditer(r"py\w*", "python and pytest use pyodide"):    print(m.group(), m.span())
Output
python (0, 6)
pytest (11, 17)
pyodide (22, 29)

Learn the concept

New to this topic? Read the lesson, then come back.

More regex programs

← All 20 RegEx Programs

Multiline and ignore-case flags

Python Practice › RegEx Programs › Program 20

Multiline and ignore-case flags

EasyRegEx Programs · 20 of 20

Write a Python program to find lines that start with “error” in any case.

Output
['Error: disk full', 'ERROR: timeout']

Approach

  1. re.M makes ^ match at every line start; re.I ignores case.

Solution

Python
import re log = "Error: disk full\ninfo: ok\nERROR: timeout\nwarning: slow"print(re.findall(r"^error:.*$", log, flags=re.M | re.I))
Output
['Error: disk full', 'ERROR: timeout']

Learn the concept

New to this topic? Read the lesson, then come back.

More regex programs

← All 20 RegEx Programs

Extract prices

Python Practice › RegEx Programs › Program 18

Extract prices

EasyRegEx Programs · 18 of 20

Write a Python program to extract rupee prices like Rs 1,499.50 and add them up.

Output
[349.0, 1499.5, 99.0] 1947.5

Approach

  1. Capture the number, remove commas, convert.

Solution

Python
import re text = "Mouse Rs 349, keyboard Rs 1,499.50, cable Rs 99"prices = [float(p.replace(",", "")) for p in re.findall(r"Rs\s?([\d,]+(?:\.\d+)?)", text)]print(prices, sum(prices))
Output
[349.0, 1499.5, 99.0] 1947.5

Learn the concept

New to this topic? Read the lesson, then come back.

More regex programs

← All 20 RegEx Programs

Find repeated words

Python Practice › RegEx Programs › Program 17

Find repeated words

EasyRegEx Programs · 17 of 20

Write a Python program to find accidentally repeated words like “the the”.

Output
['is', 'the', 'module']
This is a test of the regex module.

Approach

  1. A back-reference \1 matches the same text again.

Solution

Python
import re text = "This is is a test of the the regex module module."print(re.findall(r"\b(\w+)\s+\1\b", text))print(re.sub(r"\b(\w+)\s+\1\b", r"\1", text))
Output
['is', 'the', 'module']
This is a test of the regex module.

Learn the concept

New to this topic? Read the lesson, then come back.

More regex programs

← All 20 RegEx Programs

camelCase to snake_case

Python Practice › RegEx Programs › Program 15

camelCase to snake_case

EasyRegEx Programs · 15 of 20

Write a Python program to convert camelCase names to snake_case.

Output
firstName -> first_name
getHTTPResponse -> get_httpresponse
userIdNumber -> user_id_number

Approach

  1. Insert “_” before each capital, then lower-case.

Solution

Python
import re for name in ["firstName", "getHTTPResponse", "userIdNumber"]:    print(name, "->", re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", name).lower())
Output
firstName -> first_name
getHTTPResponse -> get_httpresponse
userIdNumber -> user_id_number

Line by line

Line 4

The look-behind and look-ahead find the gap between a lowercase letter or digit and a capital, so “HTTP” stays together.

Learn the concept

New to this topic? Read the lesson, then come back.

More regex programs

← All 20 RegEx Programs

Validate an IPv4 address

Python Practice › RegEx Programs › Program 16

Validate an IPv4 address

EasyRegEx Programs · 16 of 20

Write a Python program to check IPv4 addresses (each part 0-255).

Output
192.168.1.10 True
256.1.1.1 False
10.0.0 False
8.8.8.8 True

Approach

  1. Use regex for the shape and Python for the range.

Solution

Python
import re def is_ipv4(text):    if not re.fullmatch(r"\d{1,3}(\.\d{1,3}){3}", text):        return False    return all(0 <= int(part) <= 255 for part in text.split(".")) for ip in ["192.168.1.10", "256.1.1.1", "10.0.0", "8.8.8.8"]:    print(ip, is_ipv4(ip))
Output
192.168.1.10 True
256.1.1.1 False
10.0.0 False
8.8.8.8 True

Line by line

Lines 4-6

A regex for 0-255 is long and hard to read; checking the numbers in Python is clearer.

Learn the concept

New to this topic? Read the lesson, then come back.

More regex programs

← All 20 RegEx Programs

Mask card numbers

Python Practice › RegEx Programs › Program 14

Mask card numbers

EasyRegEx Programs · 14 of 20

Write a Python program to mask all but the last 4 digits of card numbers.

Output
Card XXXX-XXXX-XXXX-1234 and XXXX-XXXX-XXXX-9876

Approach

  1. Capture the last 4 digits and replace the rest.

Solution

Python
import re text = "Card 4111 1111 1111 1234 and 5500-0000-0000-9876"print(re.sub(r"\d{4}[ -]\d{4}[ -]\d{4}[ -](\d{4})", r"XXXX-XXXX-XXXX-\1", text))
Output
Card XXXX-XXXX-XXXX-1234 and XXXX-XXXX-XXXX-9876

Learn the concept

New to this topic? Read the lesson, then come back.

More regex programs

← All 20 RegEx Programs

Parse log lines with named groups

Python Practice › RegEx Programs › Program 13

Parse log lines with named groups

EasyRegEx Programs · 13 of 20

Write a Python program to parse “LEVEL date message” log lines into dictionaries.

Output
{'level': 'ERROR', 'date': '2026-11-02', 'msg': 'db timeout'}
{'level': 'INFO', 'date': '2026-11-02', 'msg': 'started'}

Approach

  1. Named groups and groupdict().

Solution

Python
import re LINE = re.compile(r"(?P<level>[A-Z]+) (?P<date>\d{4}-\d{2}-\d{2}) (?P<msg>.+)")for line in ["ERROR 2026-11-02 db timeout", "INFO 2026-11-02 started"]:    print(LINE.match(line).groupdict())
Output
{'level': 'ERROR', 'date': '2026-11-02', 'msg': 'db timeout'}
{'level': 'INFO', 'date': '2026-11-02', 'msg': 'started'}

Learn the concept

New to this topic? Read the lesson, then come back.

More regex programs

← All 20 RegEx Programs