javaregexroman-numerals

Java limit user input with regex


I need to limit user input of arithmetical operation with Roman numerals. The only possible input is [I to X][+-/*][I to X].

That is what I have:

boolean correctRoman = operation.matches("^(X|IX|IV|V?I{0,3}) ?[+-/*] ?(X|IX|IV|V?I{0,3})$")

What I get for different inputs:

"III"  //false
"III + "  //true-WHY??
"III + X"   //true as it should be

Thank you!


Solution

  • In this part of the pattern (X|IX|IV|V?I{0,3}) the whole last alternative is optional due to the question mark and the quantifier {0,3} allowing to match "III + "

    Note to put the - at the end of the character class or else it will match a range +-/


    You can add another alternation to match I II and III and don't make the V optional.

    ^(X|IX|IV|VI{0,3}|I{1,3}) ?[+/*-] ?(X|IX|IV|VI{0,3}|I{1,3})$
    

    Regex demo