Home > Blockchain >  How do I use RegExp to test a valid String of Roman Numeral in Dart?
How do I use RegExp to test a valid String of Roman Numeral in Dart?

Time:04-05

Following the algorithm I have, I have written the code that already converts a valid roman numeral to integer but it needs restriction on Invalid Roman Numerals such that IIII would be invalid instead of returning the integer 4.

I have written the RegExp code in python:

valid = 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})$",RomanString))
if valid:
   executes convertion...

The RegExp pattern for Dart is closer to Javascript and not python as the runTimeType of a RegExp when printed in Dart is JSSyntaxRegExp. Sources give the RegExp for validating Roman Numerals in Javascript as:

export const isRoman = (string) => {
    // regex pattern
    const pattern = /^(M{1,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})|M{0,4}(CM|C?D|D?C{1,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})|M{0,4}(CM|CD|D?C{0,3})(XC|X?L|L?X{1,3})(IX|IV|V?I{0,3})|M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|I?V|V?I{1,3}))$/
    return pattern.test(string);
};

However, the .test function for verifying the String does not exist in dart. The available ones do not bring the desired result/do not work

 String? numeral = 'iv'.toUpperCase(); ///This should be valid ///
 var pattern =  RegExp(r"/^(M{1,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})|M{0,4}(CM|C?D|D?C{1,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})|M{0,4}(CM|CD|D?C{0,3})(XC|X?L|L?X{1,3})(IX|IV|V?I{0,3})|M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|I?V|V?I{1,3}))$");
print(pattern.hasMatch(numeral)); ///Prints false irrespective of String input

CodePudding user response:

There is no way to match a slash before the beginning of a string.

Use

var pattern =  RegExp(r"^(?:M{1,4}(?:CM|CD|D?C{0,3})(?:XC|XL|L?X{0,3})(?:IX|IV|V?I{0,3})|M{0,4}(?:CM|C?D|D?C{1,3})(?:XC|XL|L?X{0,3})(?:IX|IV|V?I{0,3})|M{0,4}(?:CM|CD|D?C{0,3})(?:XC|X?L|L?X{1,3})(?:IX|IV|V?I{0,3})|M{0,4}(?:CM|CD|D?C{0,3})(?:XC|XL|L?X{0,3})(?:IX|I?V|V?I{1,3}))$");
  • Related