罗马数字和正则表达式

时间:2013-12-04 04:14:55

标签: java regex

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

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

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

2 个答案:

答案 0 :(得分:1)

这会找到第一次出现

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

答案 1 :(得分:1)

只需在输入字符串上使用带有正则表达式的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
    }
}