Using Regex Pattern to validate if a Roman number is valid
Problem Statement: Validate if a roman number is between 1 and 3999
Solution:
regex_pattern = r'^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$' # Do not delete 'r'.import reprint(str(bool(re.match(regex_pattern, input()))))
This is the classic Roman numeral validation regex (for 1–3999)
Roman Numerals
Roman numerals originated in ancient Rome and remained widely used through the Middle Ages. They rely on fixed-value symbols rather than positional notation.
Core Symbols
- I = 1
- V = 5
- X = 10
- L = 50
- C = 100
- D = 500
- M = 1000
Additive Rule
Place symbols from largest to smallest left to right:
- VIII = 5 + 1 + 1 + 1 = 8
- LXX = 50 + 10 + 10 = 70
Subtractive Rule
Place a smaller symbol before a larger one to subtract:
- IV = 4
- IX = 9
- XL = 40
- CM = 900
Common Conversions
| Number | Roman | Number | Roman |
|---|---|---|---|
| 1 | I | 20 | XX |
| 4 | IV | 40 | XL |
| 9 | IX | 90 | XC |
| 100 | C | 400 | CD |
| 500 | D | 900 | CM |
| 1000 | M | — | — |
Regex for validating Roman Numerals from 1-3999:
regex = r’^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$’
Breakdown:
^
Start of string.
M{0,3}
"" = 0M = 1000MM = 2000MMM = 3000
(CM|CD|D?C{0,3})
Hundreds place:
CM = 900CD = 400D?C{0,3}
D?C{0,3} covers:
"" = 0C = 100CC = 200CCC = 300D = 500DC = 600DCC = 700DCCC = 800
(XC|XL|L?X{0,3})
XC = 90XL = 40L?X{0,3}
L?X{0,3} covers:
"" = 0X = 10XX = 20XXX = 30L = 50LX = 60LXX = 70LXXX = 80
(IX|IV|V?I{0,3})
Ones place:
IX = 9IV = 4V?I{0,3}
covers:
"" = 0I = 1II = 2III = 3V = 5VI = 6VII = 7VIII = 8
$
End of string.
Valid Matches
IIVIXXXLXCCDCMMCMXCMCMXCIVMMMCMXCIX (3999)
Invalid Matches:
IIIIVVICXMMMMMVXILMCMC
References
Validating Roman Numerals | HackerRank
Python Regular Expressions | Python Education | Google for Developers
