Skip to content
Foxipa
Code Completion 4 Challenges

Complete the Python regular-expression code

Practice whole-string validation, named groups, lazy match iteration, and readable whitespace normalization.

Intermediate ~10 min read

Challenge 1

Validate the whole code string: exactly two uppercase letters, a hyphen, then four digits.

python Your answer
import re

code = "ZX-7042"
if :
    print("valid")
else:
    print("invalid")

Press Ctrl⌘Enter to check your answer

Challenge 2

Print the named fields captured from the full string "pens:12".

python Your answer
import re

match = re.fullmatch(r"(?P<item>[A-Za-z]+):(?P<count>\d+)", "pens:12")
if match:
    print()

Press Ctrl⌘Enter to check your answer

Challenge 3

Extract each uppercase-letter-plus-digits token from the text using Match objects.

python Your answer
import re

text = "R2 D14 Q8"
print([match.group() for match in re.finditer()])

Press Ctrl⌘Enter to check your answer

Challenge 4

Replace each run of whitespace with one space and remove whitespace at the ends.

python Your answer
import re

raw = "  alpha\t beta   gamma "
normalized = 
print(normalized)

Press Ctrl⌘Enter to check your answer