[英]Usage of Regex for phone number validation in java
I would like to implement the a phone number validation to a field in my application in java such that the field allows only the phone number in the format "+543353453".我想对我的应用程序中的字段执行电话号码验证,以便该字段仅允许格式为“+543353453”的电话号码。
I would like to do it using Regular expressions but Regex are a bit confusing to me.我想用正则表达式来做,但正则表达式让我有点困惑。
The below code does not work.下面的代码不起作用。
public static void main(String args[])
{
String a[]=new String[]{"+90030","3434","+403403"};
String regEx="\\+\\d{9}";
pattern = Pattern.compile(regEx);
for(int i=0;i<a.length;i++)
{
boolean matches=pattern.equals(a[i]);
if(pattern.equals(a[i]))
System.out.println("Phone number is valid"+a[i]);
else
System.out.println("Phone number is invalid"+a[i]);
}
}
}
Use this code:使用此代码:
public static void main(String args[]) {
String a[] = new String[] { "+90030", "3434", "+403403", "+477777777" };
String regEx = "\\+\\d{9}";
Pattern pattern = Pattern.compile(regEx);
for (int i = 0; i < a.length; i++) {
boolean matches = pattern.matcher(a[i]).matches();
if (matches)
System.out.println("Phone number is valid" + a[i]);
else
System.out.println("Phone number is invalid" + a[i]);
}
}
And spend some time reading the doc, you were comparing a pattern and a String, they could not be equal.并花一些时间阅读文档,您正在比较模式和字符串,它们不可能相等。 And finally, in your test case, add at least a case which passes the validation.
最后,在您的测试用例中,至少添加一个通过验证的用例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.