🐍 Python for Everyone

← Back to practice bank

Chapter 18 Coding Challenges 55-70 min, auto-graded

Coding Challenges: Regular Expressions

8 HackerRank-style challenges, auto-graded right in your browser — no setup required. Write your function in the code box, then click Run Tests to check it against a set of test cases (including edge cases). Stuck? Every challenge has a Show Solution reveal at the bottom. Only uses what Chapters 1-18 have covered so far — including import re and every re function and pattern feature from this chapter's lesson. No import beyond re/math/datetime/random/csv.

How grading works Your code runs entirely in your browser using Pyodide (Python compiled to WebAssembly) — nothing is uploaded anywhere. Keep the function name in the stub exactly as given, since the grader calls it by name.

1 Valid Email Checker Easy

Write a function is_valid_email(text) that returns whether text, in its entirety, looks like a valid email address: one or more letters/digits/./+/-/_, then an @, then one or more letters/digits/-, then a literal dot, then 2 or more letters. Use re.fullmatch() with the pattern r"[\w.+-]+@[\w-]+\.[A-Za-z]{2,}" and return whether the result is not None.

Constraints: text is always a string, possibly empty.
Examples:
is_valid_email("ann@example.com") → true
is_valid_email("not-an-email") → false
challenge_1.py
Show Solution
solution_1.py
import re

def is_valid_email(text):
    return re.fullmatch(r"[\w.+-]+@[\w-]+\.[A-Za-z]{2,}", text) is not None

2 Extract Every Number Easy

Write a function extract_numbers(text) that returns every run of one or more digits found in text, as a list of strings, in the order they appear. Use re.findall() with the pattern r"\d+".

Constraints: text may be empty or contain no digits at all, in which case return an empty list.
Examples:
extract_numbers("Room 42 has 7 chairs") → ["42", "7"]
extract_numbers("no numbers here") → []
challenge_2.py
Show Solution
solution_2.py
import re

def extract_numbers(text):
    return re.findall(r"\d+", text)

3 Word Counter via Regex Easy

Write a function count_words(text) that returns how many words are in text, using len(re.findall(r"\b\w+\b", text)) — a word being any run of letters/digits/underscores bounded by word boundaries, regardless of how much whitespace separates them.

Constraints: text may be empty or contain irregular spacing (multiple spaces, leading/trailing spaces).
Examples:
count_words("one two three") → 3
count_words("") → 0
challenge_3.py
Show Solution
solution_3.py
import re

def count_words(text):
    return len(re.findall(r"\b\w+\b", text))

4 Mask Every Phone Number Medium

Write a function mask_phone_numbers(text) that replaces every phone number shaped like ###-###-#### in text with "XXX-XXX-XXXX", using re.sub().

Constraints: text may contain zero, one, or several phone numbers, or none at all.
Examples:
mask_phone_numbers("Call 555-123-4567 or 555-987-6543") → "Call XXX-XXX-XXXX or XXX-XXX-XXXX"
mask_phone_numbers("no numbers") → "no numbers"
challenge_4.py
Show Solution
solution_4.py
import re

def mask_phone_numbers(text):
    return re.sub(r"\d{3}-\d{3}-\d{4}", "XXX-XXX-XXXX", text)

5 Split on Multiple Delimiters Medium

Write a function split_on_multiple_delimiters(text) that splits text wherever a comma or semicolon appears, optionally followed by whitespace, using re.split() with the pattern r"[,;]\s*". Return the resulting list.

Constraints: text may use a mix of commas and semicolons, with or without spaces after them.
Examples:
split_on_multiple_delimiters("apple,banana; cherry, date") → ["apple", "banana", "cherry", "date"]
split_on_multiple_delimiters("single") → ["single"]
challenge_5.py
Show Solution
solution_5.py
import re

def split_on_multiple_delimiters(text):
    return re.split(r"[,;]\s*", text)

6 Extract Every Hashtag Easy

Write a function extract_hashtags(text) that returns every hashtag in text (a # followed by one or more letters/digits/underscores), as a list of strings, using re.findall() with the pattern r"#\w+".

Constraints: text may contain zero, one, or several hashtags.
Examples:
extract_hashtags("Loving this #sunset and #BeachLife") → ["#sunset", "#BeachLife"]
extract_hashtags("no hashtags") → []
challenge_6.py
Show Solution
solution_6.py
import re

def extract_hashtags(text):
    return re.findall(r"#\w+", text)

7 Parse a Log Line Into Named Fields Medium

Write a function parse_log_line(line) that matches line against the pattern r"(?P<time>\d{2}:\d{2}:\d{2})\s+\[(?P<level>\w+)\]\s+(?P<message>.+)" using re.match(). If it matches, return match.groupdict() (a dict with keys "time", "level", and "message"). If it doesn't match, return None.

Constraints: line may not be in the expected log format at all, in which case return None.
Examples:
parse_log_line("10:15:00 [ERROR] disk full") → {"time": "10:15:00", "level": "ERROR", "message": "disk full"}
parse_log_line("not a log line") → null
challenge_7.py
Show Solution
solution_7.py
import re

def parse_log_line(line):
    match = re.match(
        r"(?P

8 First N Matches, Using a Compiled Pattern Medium

Write a function first_n_matches(text, pattern, n) that builds a compiled pattern with re.compile(pattern), then loops over compiled.finditer(text), collecting each match's .group() into a list, and stopping (breaking out of the loop) once the list already has n items — even if more matches remain in text. Return the list.

Constraints: there may be fewer than n matches total in text, in which case return only however many were actually found.
Examples:
first_n_matches("a1 b2 c3 d4 e5", r"[a-z]\d", 3) → ["a1", "b2", "c3"]
first_n_matches("no matches", r"\d+", 2) → []
challenge_8.py
Show Solution
solution_8.py
import re

def first_n_matches(text, pattern, n):
    compiled = re.compile(pattern)
    results = []
    for match in compiled.finditer(text):
        if len(results) >= n:
            break
        results.append(match.group())
    return results
← Practice Bank Interview Questions →