user2187875
user2187875

Reputation:

roman numerals and regex

I am working on a program that determines is a entered string is a roman numeral. my issue is that in the following code

    public void romancheck(String num){
    if(num.isEmpty()){
        JOptionPane.showMessageDialog(null, "No number typed");
    }
    if (num.matches("[IVXLCDM]+")){
        repeatefinder(num);
       if(repeated == 'I' || repeated == 'V' || repeated == 'X' || repeated == 'L' || repeated == 'C' || repeated == 'D' || repeated == 'M'){
        JOptionPane.showMessageDialog(null, repeated + " is repeated more than three times in " + num);
       }
       else{
           JOptionPane.showMessageDialog(null, num + " is a roman number"); 
       }
    }
    if(){
        JOptionPane.showMessageDialog(null,  + " is not a roman number in " + num);
}
}

I use the regex num.matches("[IVXLCDM]+") to determine if the entered string only contains roman numeral chars my issue is i want to print a message if a char in the string is not a roman numeral char using the last if statement. what would be the most effective way to find the chars in the string that are not roman numeral chars?

Upvotes: 2

Views: 2121

Answers (2)

Josiah Hester
Josiah Hester

Reputation: 6095

Just use replaceAll with your regex on the input string, so that only characters that are not roman numerals are left over, with underscores between to preserve the index:

String notRomanNumerals = num.replaceAll("[IVXLCDM]+", "_"); 
System.out.println("Error: not all characters are roman numerals: "+  notRomanNumerals);

If then you want the index of the character in the string, then just do

for(int i=0;i<notRomanNumerals.length;i++) {
    if(notRomanNumerals.charAt(i) != '_') {
        // i is an index of a char that is not a roman numeral
        // Do what you want with it
    }
}

Upvotes: 1

Paul Draper
Paul Draper

Reputation: 83205

This finds the first occurance

else {
    Matcher matcher = Pattern.compile("[^IVXLCDM]").matcher();
    matcher.find();
    JOptionPane.showMessageDialog(null, matcher.group() + " is not a roman number in " + num);
}

This finds all occurances

else {
    JOptionPane.showMessageDialog(null, num.replaceAll("[^IVXLCDM]", "") + " are not roman numbers in " + num);
}

Upvotes: 1

Related Questions