Categories
Coding Computer Science Python

Solving Problem: Validating Roman Numbers

Using Regex Pattern to validate if a Roman number is valid

Problem Statement: Validate if a roman number is between 1 and 3999

Solution:

Python
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 re
print(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
NumberRomanNumberRoman
1I20XX
4IV40XL
9IX90XC
100C400CD
500D900CM
1000M——

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}

"" = 0
M = 1000
MM = 2000
MMM = 3000

(CM|CD|D?C{0,3})

Hundreds place:

CM = 900
CD = 400
D?C{0,3}

D?C{0,3} covers:

"" = 0
C = 100
CC = 200
CCC = 300
D = 500
DC = 600
DCC = 700
DCCC = 800

(XC|XL|L?X{0,3})

XC = 90
XL = 40
L?X{0,3}

L?X{0,3} covers:

"" = 0
X = 10
XX = 20
XXX = 30
L = 50
LX = 60
LXX = 70
LXXX = 80

(IX|IV|V?I{0,3})

Ones place:

IX = 9
IV = 4
V?I{0,3}

covers:

"" = 0
I = 1
II = 2
III = 3
V = 5
VI = 6
VII = 7
VIII = 8

$

End of string.

Valid Matches

I
IV
IX
X
XL
XC
CD
CM
MCMXC
MCMXCIV
MMMCMXCIX (3999)

Invalid Matches:

IIII
VV
IC
XM
MMMM
VX
IL
MCMC

Validating Roman Numerals | HackerRank

Python Regular Expressions  |  Python Education  |  Google for Developers

Priyanka B.'s avatar

By Priyanka B.

Hello and welcome to my little corner of internet!! I am a techie. I am very interested to discover and innovate new advances in science and technology. Blogging is one of my hobbies which I think is very useful for broadening my knowledge horizons and help me grow my skills. Apart from blogging I have also little taste in artistic skills and literature, which can keep my writing and posts tangy.

Whether you stumbled in by chance or came here on purpose, I hope you find something that sparks your curiosity or makes you think a little deeper. Thanks for stopping by!!

Leave a Reply

Discover more from StellarRimz

Subscribe now to keep reading and get access to the full archive.

Continue reading