Java 罗马数字和正则表达式

Java 罗马数字和正则表达式,java,regex,Java,Regex,我正在开发一个程序,确定输入的字符串是罗马数字。我的问题是,在下面的代码中 public void romancheck(String num){ if(num.isEmpty()){ JOptionPane.showMessageDialog(null, "No number typed"); } if (num.matches("[IVXLCDM]+")){ repeatefinder(num); if(repea

我正在开发一个程序,确定输入的字符串是罗马数字。我的问题是,在下面的代码中

    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);
}
}

我使用regex
num.matches(“[IVXLCDM]+”)
确定输入的字符串是否只包含罗马数字字符我的问题是,如果字符串中的字符不是罗马数字字符,我想使用最后一个if语句打印消息。找到字符串中不是罗马数字字符的字符的最有效方法是什么?

这会找到第一个出现的字符

else {
    Matcher matcher = Pattern.compile("[^IVXLCDM]").matcher();
    matcher.find();
    JOptionPane.showMessageDialog(null, matcher.group() + " is not a roman number in " + num);
}
这会发现所有发生的事情

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

只需对输入字符串上的正则表达式使用
replaceAll
,这样就只剩下非罗马数字的字符,中间加下划线以保留索引:

String notRomanNumerals = num.replaceAll("[IVXLCDM]+", "_"); 
System.out.println("Error: not all characters are roman numerals: "+  notRomanNumerals);
如果您想要字符串中字符的索引,那么只需执行以下操作

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
    }
}

for(int i=0;i+1),但您的“show index of”代码不会处理同一个无效字符的多次出现。是的,刚刚意识到,已更新,以便为索引os提供所有无效字符