Search code examples
javaregexroman-numeralsmvel

String replace for Roman numerals


I am getting user Input like following.

"Both ix is viii are roman numeral. mcmlxxxvii is wow year. Year is mmxvi."

I have to search all roman numerals present in i/p and convert it to upper case. So i want to use string replace like below where xxx an be found roman numeric.

input.replaceAll("(?i)xxx","XXX");

Currently, i am able to check if input is having it or not.

System.out.println(input.matches("^.*M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3}).*$"));

Help me in this.


Solution

  • Try this:

    (?!\bi+\b)\b[dcmlxvi]+\b|(\bi+\.)
    

    and replace by this:

    \U\1 will not work in java though,but the following code will
    

    Explanation

    java code sample:

    final String regex = "(?!\\bi+\\b)\\b[dcmlxvi]+\\b|(\\bi+\\.)";
    String string = "i i Both ix is viii are roman numeral. mcmlxxxvii is wow year. Year is mmxvi. i i I i i i i am good";
    String tmp;
    final Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
    final Matcher matcher = pattern.matcher(string);
    
    while (matcher.find()) {
        tmp=matcher.group(0).toUpperCase();
        string=string.replace(matcher.group(0),tmp);
    }
    
    System.out.println(string);