[英]Getting a name as an input using regex in java
我是Java和正則表達式的初學者。 我想獲取一個名稱作為輸入,這意味着僅具有英文字母AZ,不區分大小寫和空格的名稱。
我正在使用Scanner
類來獲取輸入,但是我的代碼不起作用。 看起來像:
Scanner sc= new Scanner(System.in);
String n;
while(!sc.hasNext("^[a-zA-Z ]*$"))
{
System.out.println("That's not a name!");
sc.nextLine();
}
n = sc.next();
我在regex101.com網站上檢查了我的正則表達式,發現它可以正常工作。
例如,如果我輸入我的名字Akshay Arora
,則正則表達式網站說可以,但是我的程序可以打印
That's not a name
That's not a name
同一行打印兩次,然后再次要求我輸入。 我要去哪里錯了?
有兩個部分是錯誤的:
$
和^
錨是在整個輸入的上下文中考慮的,而不是在下一個標記的上下文中考慮的。 除非輸入的一行與整個模式完全匹配,否則它將永遠不會匹配。 Scanner
將永遠不會返回帶有空格的令牌。 解決方法如下:
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\n");
String n;
while(!sc.hasNext("[a-zA-Z ]+"))
{
System.out.println("That's not a name!");
sc.nextLine();
}
n = sc.next();
這里的示例程序與正則表達式有關。
public class Program {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String inputName = sc.next();
String regex = "^[a-zA-Z ]*$";
// Compile this pattern.
Pattern pattern = Pattern.compile(regex);
// See if this String matches.
Matcher m = pattern.matcher(inputName);
if (m.matches()) {
System.out.println("Valid Name");
} else
System.out.println("Invalid Name");
}
}
希望這個能對您有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.