Validate Roman Numerals Using Regular Expression in Python

In this tutorial, we will learn whether a given roman numeral is valid or not using regular expression in Python.

Roman numerals are the number framework that started in old Rome. These numbers are extraordinarily found in old records. Shakespeare utilized Roman numerals to list his plays. These sorts of numbers are spoken to with the assistance of letters in order.

Roman numerals are based on the following symbols

SYMBOL             VALUE
I                    1
IV                   4
V                    5
IX                   9
X                    10
XL                   40
L                    50
XC                   90
C                    100
CD                   400
D                    500
CM                   900
M                    1000

Validating Roman Numerals Using Regular Expression in Python

The regular expression that is used to check if a string is a Valid Roman Number is

^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$

Where

  • M{0,3} is used to check the thousand’s place.
  • (CM|CD|D?C{0,3}) is used to check the hundred’s place.
  • (XC|XL|L?X{0,3}) is used to check the tens place.
  • (IX|IV|V?I{0,3}) is used to check the unit’s place.

Approach:

1. Import the regular expression module.

2. Now, search the input string in the expression.

3. Finally, return the true if expression found else, false.

import re

def valid_roman_numeral(string):
    return (re.search(r"^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$",string))

string = input("Enter the string: ")
if(valid_roman_numeral(string)):
    print("Valid Roman Numeral")
else:
    print("Not a valid roman numeral")

Output

Enter the string: IV
Valid Roman Numeral

Enter the string: AX
Not a valid roman numeral

Also, refer

Leave a Reply

Your email address will not be published.