Open In App

Validating Roman Numerals Using Regular expression

Last Updated : 27 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a String, and You have to validate whether the given String is Valid Roman Numeral or not. If it is valid print True else False.
Note: Numerals are lying between 1 to 3999.
Examples: 
 

Input: String = IX  
Output: True 

Input: String = 54IVC 
Output: False

 

Roman numerals are based on below 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       

A number in Roman Numerals is a string of these symbols written in descending order(e.g. M’s first, followed by D’s, etc.). However, in a few specific cases, to avoid four characters being repeated in succession (such as IIII or XXXX), subtractive notation is often used as follows: 
 

  • I placed before V or X indicates one less, so four is IV (one less than 5) and 9 is IX (one less than 10).
  • X placed before L or C indicates ten less, so forty is XL (10 less than 50) and 90 is XC (ten less than a hundred).
  • C placed before D or M indicates a hundred less, so four hundred is CD (a hundred less than five hundred) and nine hundred is CM (a hundred less than a thousand).

Approach: 

  • The Regular Expression to check if a string is Valid Roman Numeral or not is this: 
 ^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$
  • In which, 
    1. M{0,3} specifies the thousands section and basically restrains it to between 0 and 4000 
       
    2. (CM|CD|D?C{0,3}) is for the hundreds section. 
       
    3. (XC|XL|L?X{0,3}) is for the tens place. 
       
    4. Finally, (IX|IV|V?I{0,3}) is the units section. 
       
  • Import regular expression and search the input string in the expression if the string exists return True else return False 
     

Below is the implementation of the above approach.

C++




// C++ program to validate the
//  Roman numeral
 
#include <iostream>
#include <regex>
using namespace std;
 
// Function to validate the
// Roman numeral
bool ValidationOfRomanNumerals(string str)
{
 
    // Regex to check valid
    // ROMAN NUMERAL .
    const regex pattern("^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$");
 
    // If the str
    // is empty return false
    if (str.empty()) {
        return false;
    }
 
    // Return true if the str
    // matched the ReGex
    if (regex_match(str, pattern)) {
        return true;
    }
    else {
        return false;
    }
}
 
// Driver Code
int main()
{
   
    // Test Case 1:
    string str1 = "IX";
    cout << ValidationOfRomanNumerals(str1) << endl;
 
    return 0;
}
 
// This code is contributed by rahulchauhan2020model.


Java




// Java program to validate the
// the Roman numeral
import java.util.regex.*;
 
class GFG {
 
  // Function to Validate the Roman numeral
  public static boolean
    ValidationOfRomanNumerals(String str)
  {
 
    // Regex to check Roman numeral
    String regex
      = "^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$";
 
    // Compile the ReGex
    Pattern p = Pattern.compile(regex);
 
    // If the str
    // is empty return false
    if (str == null) {
      return false;
    }
 
    // Pattern class contains matcher() method
    // to find matching between given
    // ROMAN NUMERAL regular expression.
    Matcher m = p.matcher(str);
 
    // Return if the str
    // matched the ReGex
    return m.matches();
  }
 
  // Driver Code.
  public static void main(String args[])
  {
 
    // Test Case 1:
    String str1 = "IX";
    System.out.println(
      "IS " + str1 + " valid ROMAN NUMERAL:? "
      + ValidationOfRomanNumerals(str1));
  }
}
 
// This code is contributed by rahulchauhan2020model.


Python3




# Python3 program to Validate the Roman numeral
 
# Function to Validate the Roman numeral
def ValidationOfRomanNumerals(string):
     
    # Importing regular expression
    import re
     
    # Searching the input string in expression and
    # returning the boolean value
    print(bool(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)))
 
# Driver code
 
# Given string
string="XI"
 
# Function call
ValidationOfRomanNumerals(string)


C#




// C# program to validate
// the Roman numeral using Regular Expression
using System;
using System.Text.RegularExpressions;
class GFG
{
 
  // Main Method
  static void Main(string[] args)
  {
 
    // Input strings to Match
    //the Roman numeral
  
    string[] str={"IX"};
    foreach(string s in str) {
      Console.WriteLine( ValidationOfRomanNumerals(s) ? "true" : "false");
    }
    Console.ReadKey(); }
 
  // method containing the regex
  public static bool ValidationOfRomanNumerals(string str)
  {
    string strRegex = @"^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$";
    Regex re = new Regex(strRegex);
    if (re.IsMatch(str))
      return (true);
    else
      return (false);
  }
}
 
// This code is contributed by Rahul Chauhan


Javascript




// Javascript program to validate
// ROMAN NUMERAL using Regular Expression
 
// Function to validate the
// ROMAN NUMERAL
function ValidationOfRomanNumerals(str)
{
 
    // Regex to check valid
    // ROMAN NUMERAL
    let regex = new RegExp(/^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/);
 
    // str
    // is empty return false
    if (str == null) {
        return "false";
    }
 
    // Return true if the str
    // matched the ReGex
    if (regex.test(str) == true) {
        return "true";
    }
    else {
        return "false";
    }
}
 
// Driver Code
// Test Case 1:
let str1 = "XI";
console.log(ValidationOfRomanNumerals(str1));
 
// This code is contributed by rahulchauhan2020model.


Output: 

True

 

Time Complexity: O(N) where N is the length of the given string. 
Auxiliary Space: O(1)  



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads