[英]How to use Pattern.matches with regex to filter unwanted characters in a string
我正在为一个类编写程序,该类需要我们将输入字符串传递给Integer.parseInt函数。 在移交字符串之前,我想确保它不包含任何非数字值。 我使用Pattern.matches创建了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."));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.