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.
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.
text is always a string, possibly empty.
is_valid_email("ann@example.com") → trueis_valid_email("not-an-email") → false
Show Solution
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+".
text may be empty or contain no digits at all, in which case return an empty list.
extract_numbers("Room 42 has 7 chairs") → ["42", "7"]extract_numbers("no numbers here") → []
Show Solution
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.
text may be empty or contain irregular spacing (multiple spaces, leading/trailing spaces).
count_words("one two three") → 3count_words("") → 0
Show Solution
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().
text may contain zero, one, or several phone numbers, or none at all.
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"
Show Solution
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.
text may use a mix of commas and semicolons, with or without spaces after them.
split_on_multiple_delimiters("apple,banana; cherry, date") → ["apple", "banana", "cherry", "date"]split_on_multiple_delimiters("single") → ["single"]
Show Solution
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+".
text may contain zero, one, or several hashtags.
extract_hashtags("Loving this #sunset and #BeachLife") → ["#sunset", "#BeachLife"]extract_hashtags("no hashtags") → []
Show Solution
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.
line may not be in the expected log format at all, in which case return None.
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
Show Solution
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.
n matches total in text, in which case return only however many were actually found.
first_n_matches("a1 b2 c3 d4 e5", r"[a-z]\d", 3) → ["a1", "b2", "c3"]first_n_matches("no matches", r"\d+", 2) → []
Show Solution
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