Regex Pattern:
^Part (?:[IVXLCDM]{1,4}|M{0,3}(?:CM|CD|D?C{0,3})(?:XC|XL|L?X{0,3})(?:IX|IV|V?I{0,3}))$
Let's break it down:
Explanation:
^ asserts the start of the string.
Part matches the literal string "Part " (with a space) where "P" is uppercase.
(?:) is a non-capturing group that contains the Roman numeral pattern.
- We use two approaches combined with an alternation
| to match Roman numerals up to 4 characters:
[IVXLCDM]{1,4} matches any Roman numeral character (I, V, X, L, C, D, M) between 1 and 4 times. However, this is a very lenient approach and would match invalid Roman numerals like "IIIV".
- The longer part
M{0,3}(?:CM|CD|D?C{0,3})(?:XC|XL|L?X{0,3})(?:IX|IV|V?I{0,3}) is a more precise pattern that matches valid Roman numerals. Here's how it works:
M{0,3} matches 0 to 3 "M"s (1000, 2000, 3000).
(?:CM|CD|D?C{0,3}) matches the hundreds place:
CM = 900, CD = 400.
D?C{0,3} = 0, 100, 200, 300, 500, 600, 700, 800 (optional "D" followed by 0 to 3 "C"s).
(?:XC|XL|L?X{0,3}) matches the tens place:
XC = 90, XL = 40.
L?X{0,3} = 0, 10, 20, 30, 50, 60, 70, 80 (optional "L" followed by 0 to 3 "X"s).
(?:IX|IV|V?I{0,3}) matches the ones place:
IX = 9, IV = 4.
V?I{0,3} = 0, 1, 2, 3, 5, 6, 7, 8 (optional "V" followed by 0 to 3 "I"s).
$ asserts the end of the string, ensuring no extra characters are present.
Example Use Cases in Python:
import re
# Regex pattern
pattern = r"^Part (?:[IVXLCDM]{1,4}|M{0,3}(?:CM|CD|D?C{0,3})(?:XC|XL|L?X{0,3})(?:IX|IV|V?I{0,3}))$"
# Test valid matches
valid_inputs = [
"Part I",
"Part V",
"Part XIII",
"Part XX",
"Part MMXXIII"
]
for text in valid_inputs:
if re.match(pattern, text):
print(f"Matched: {text}")
else:
print(f"Not matched: {text}")
# Test invalid matches
invalid_inputs = [
"Part 123", # Not Roman numerals
"part I", # Lowercase "p"
"Part ABC", # Not Roman numerals
"Part MMMM", # Exceeds 4 chars and invalid Roman numeral
"Part" # Missing Roman numeral
]
for text in invalid_inputs:
if re.match(pattern, text):
print(f"Matched: {text}")
else:
print(f"Not matched: {text}")
Output:
Matched: Part I
Matched: Part V
Matched: Part XIII
Matched: Part XX
Matched: Part MMXXIII
Not matched: Part 123
Not matched: part I
Not matched: Part ABC
Not matched: Part MMMM
Not matched: Part
Notes:
- The alternation
| allows the regex to match either any 1-4 Roman numeral characters (fast but permissive) or a strictly valid Roman numeral (slower but accurate).
- If performance is critical and you expect mostly valid Roman numerals, remove the
[IVXLCDM]{1,4} part and stick with the longer, precise pattern.
- This regex ensures:
- Only uppercase "P" in "Part".
- A space after "Part".
- Roman numerals are valid (e.g., "IV", "IX", "XL", not "IIIV").
- The numeral part does not exceed 4 characters (e.g., "MMXX" is okay, "MMMM" is not).
Now you're ready to match strings like "Part XIV" with surgical precision! 😄