我正在学习Java正则表达式,并且在下面的程序中期望使用list [4]项目
"Its a valid number : +11234562222"
,但打印为无效。我做了-在正则表达式(\\+\\d{1,2}-?)
中是可选的。谁能指出该代码中缺少什么?
当前输出
> Its a valid number : 123-456-2222
Its a valid number : +1-123-456-2222
Its a valid number : 1234562222
Its a invalid number : 12345622226
Its a invalid number : +11234562222
预期产量
> Its a valid number : 123-456-2222
Its a valid number : +1-123-456-2222
Its a valid number : 1234562222
Its a invalid number : 12345622226
Its a valid number : +11234562222
public static void vali_mobile_num(){
String mob_pat = "^(\\+\\d{1,2}-?)?+(\\d{3}-?){2}+\\d{4}$";
List list = new ArrayList();
list.add( "123-456-2222");
list.add("+1-123-456-2222");
list.add("1234562222");
list.add("12345622226");
list.add("+11234562222");
Pattern p = Pattern.compile(mob_pat);
list.forEach(x -> {
Matcher m = p.matcher(x.toString());
if(m.find()){
System.out.println("Its a valid number : "+m.group());
}
else
System.out.println("Its a invalid number : "+ x);
});
}
答案 0 :(得分:1)
您的正则表达式几乎可以用,除了您多了+
我不明白为什么。只需删除它,这很好。
^(\\+\\d{1,2}-?)?+(\\d{3}-?){2}+\\d{4}$
^ is not needed
尝试此Java代码,
List<String> list = Arrays.asList("123-456-2222","+1-123-456-2222","1234562222","12345622226","+11234562222");
Pattern p = Pattern.compile("^(\\+\\d{1,2}-?)?(\\d{3}-?){2}+\\d{4}$");
list.forEach(x -> {
Matcher m = p.matcher(x);
if(m.matches()) {
System.out.println(x + " is Valid");
} else {
System.out.println(x + " is Invalid");
}
});
打印
123-456-2222 is Valid
+1-123-456-2222 is Valid
1234562222 is Valid
12345622226 is Invalid
+11234562222 is Valid