Python RegEx

Use the built-in re module in all tasks.


1) Import and Match

Write a program to import re and check if the string "hello" matches the pattern "hello" using re.match().


2) Search for Substring

Ask the user for a text. Search for the substring "cat" using re.search() and print whether it was found.


3) Find All Digits

Given the string "a1b2c3", use re.findall() to extract all digits.

Expected:

['1', '2', '3']

4) Extract Letters Only

From "abc123xyz", extract only the alphabetic letters.


5) First Match Only

Use re.search() to find the first occurrence of any vowel (a,e,i,o,u) in "bcdfae" and print its position (index).


6) Match at Start

Use re.match() to check if a string starts with "202".


7) Validate Simple Email

Write a regex to check if an input string is a simple email containing letters, digits, @, and . (basic validation).

Example:


8) Find Words of Length √

From "one two three", find all words of exactly three letters.

Expected:


9) Replace Digits

Replace all digits in "abc123xyz" with "*", then print the result.


10) Split on Spaces

Take a sentence and split it into words using re.split() where spaces may be multiple.


11) Check Numeric String

Ask for input and print True if the string contains only digits (no letters).


12) Find Words Beginning With Capital

From "Hello World Python regex", extract words that start with a capital letter.

Expected:


13) Count Vowels

Use regex to find all vowels in a text and print the count.


14) Strip Non-Alphanumeric

Given "@hello! Python#", remove anything that isn’t a letter or digit.

Requested output:


15) Find Repeated Characters

In "baalloon", find characters that repeat (like aa or ll).


16) Extract Extensions

Given a list of filenames:

Extract the file extensions using regex.


17) Validate Simple Phone Number

Validate if input matches:

where x is a digit.

Example valid:


18) Find Words With Numbers

From "abc 123 def45 ghi", only extract tokens that contain at least one digit.

Expected:


19) Remove Extra Spaces

Given:

use regex to reduce multiple spaces to a single space.


20) Extract Time Format

From "The time is 12:45 pm", extract the time (12:45) using regex.


🧠 Regex Concepts Practiced

Task Type
Example Pattern

Literal match

"hello"

Character classes

[a-z], \d

Word boundaries

\bword\b

Vowels

[aeiou]

Start of string

^pattern

End of string

pattern$

Repetition

+, *, {n}

Groups & extraction

(...)

Replace

re.sub()

Split

re.split()


🧪 Python re Usage Template

Importing

Match at start

Search anywhere

Find all

Replace

Split


canvil: 333f6c7d-6876-4f7e-b6ad-1bdb2233f5c1

Last updated