Pat*_*tch 3 java regex string validation character
我遇到的问题是当我检查字符串是否包含任何字符时,它只查看第一个字符而不是整个字符串.例如,我希望能够输入"123abc",并且字符被识别,因此失败.我还需要字符串长度为11个字符,因为我的程序只能使用1个字符,所以它不能再进一步了.
到目前为止,这是我的代码:
public static int phoneNumber(int a)
{
while (invalidinput)
{
phoneNumber[a] = myScanner.nextLine();
if (phoneNumber[a].matches("[0-9+]") && phoneNumber[a].length() == 11 )
{
System.out.println("Continue");
invalidinput = false;
}
else
{
System.out.print("Please enter a valid phone number: ");
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
例如,为什么如果我拿走检查看到phoneNumber.length()它仍然只注册1个字符,所以如果我输入"12345"它仍然失败.我只能输入"1"才能继续该程序.
如果有人可以向我解释这对我有用,那会很棒
你regex和if condition是错误的.像这样使用它:
if ( phoneNumber[a].matches("^[0-9]{11}$") ) {
System.out.println("Continue");
invalidinput = false;
}
Run Code Online (Sandbox Code Playgroud)
这只允许phoneNumber[a]11个字符长,仅包含数字0-9