如何使用带有正则表达式的Pattern.matches来过滤字符串中不需要的字符

时间:2013-11-03 00:59:24

标签: java regex

我正在研究一个类的程序,该程序要求我们将输入字符串传递给Integer.parseInt函数。在我关闭字符串之前,我想确保它不包含任何非数字值。我用Pattern.matches创建了这个函数来尝试这个。这是代码:

while((Pattern.matches("[^0-9]+",inputGuess))||(inputGuess.equals(""))) //Filter non-numeric values and empty strings.
                {
                    JOptionPane.showMessageDialog(null, "That is not a valid guess.\nPlease try again.");
                    inputGuess=(JOptionPane.showInputDialog(null, "Enter your guess.\nPlease enter a numeric value between 1 and 12."));
                }

每当我输入任何字母,标点符号或“特殊字符”时,while语句就会生效。但是,每当我引入任何字母组合,标点符号或“特殊字符”和数字时,程序就会崩溃并烧毁。我的问题是:有没有办法使用正则表达式的Pattern.matches,这将允许我防止数字和字母,标点符号或“特殊字符”的任何组合被交给Integer.parseInt,但仍然只允许数字传递给Integer.parseInt。

2 个答案:

答案 0 :(得分:1)

试试这个:

!Pattern.matches("[0-9]+",inputGuess)

或者更简洁:

!Pattern.matches("\\d+",inputGuess)

使用+也不需要检查空字符串。

请注意,Integer.parseInt仍有可能失败并超出界限。

为了防止这种情况,您可以

!Pattern.matches("\\d{1,9}",inputGuess)

虽然这排除了一些大的有效整数值(任何十亿或更多)。

老实说,我会在Integer.parseInt使用try-catch并在必要时检查其标志。

答案 1 :(得分:0)

您的程序无效,因为Pattern.matches要求整个字符串与模式匹配。相反,即使字符串的单个子字符串与您的模式匹配,您也希望显示错误。

这可以通过Matcher

来完成
public static void main(String[] args) {
    Pattern p = Pattern.compile("[^\\d]");

    String inputGuess = JOptionPane.showInputDialog(null, "Enter your guess.\nPlease enter a numeric value between 1 and 12.");

    while(inputGuess.equals("") || p.matcher(inputGuess).find()) //Filter non-numeric values and empty strings.
    {
        JOptionPane.showMessageDialog(null, "That is not a valid guess.\nPlease try again.");
        inputGuess=(JOptionPane.showInputDialog(null, "Enter your guess.\nPlease enter a numeric value between 1 and 12."));
    }
}