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!
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})$
^
Start of string(X|IX|IV|VI{0,3}|I{1,3})
Match roman numerals 10, 9, 4, 5-8 and 1-3 ?[+/*-] ?
Match one of the characters between optional spaces(X|IX|IV|VI{0,3}|I{1,3})
The same number numbers as the first part$
End of string