我正在尝试在 while 循环中使用正则表达式来验证用户输入。我试图只接受一个小写单词(包括字母 a-z)。
public class testRedex{
public static void main(String [] args){
Scanner console = new Scanner(System.in);
System.out.print("Please enter a key: ");
while(!console.hasNext("[a-z]+")){
System.out.println("Invalid key");
console.next();
}
String test = console.next();
System.out.println(test);
}
}
我的问题是,正则表达式“[a-z]+”和“[a-z]+$”有什么区别吗?我知道 $ 会在字符串末尾查找 a-z 之间的字符,但在这种情况下这会重要吗?
最佳答案
是的,有区别,如果您使用:^[a-z]+$
,则意味着用户输入的任何内容都应仅从[a-z]+
组合>.
如果您不添加 ^
和 $
,用户可以插入其他字符,例如空格,并且仍然会匹配(第一部分字符串直到空格。
让我们看一个例子:
- 使用输入运行代码:“try this”(它将打印“try”)
- 现在将正则表达式更改为
^[a-z]+$
并使用相同的输入运行(它将打印“无效 key ”)。
我重写它的方式是:
System.out.print("Please enter a key: ");
String test = console.nextLine();
while (!test.matches("^[a-z]+$")) {
System.out.println("Invalid key");
test = console.nextLine();
}
System.out.println(test);
关于java - Java中的正则表达式: Validating user input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24592808/