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



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

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。

试试这个:

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

或者更简洁地说:

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

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

请注意,Integer.parseInt仍有可能因越界而失败。

为了防止这种情况,你可以做

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

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

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

您的程序不起作用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."));
    }
}

最新更新