gpt4 book ai didi

java - Java Regex电话号码验证

转载 作者:行者123 更新时间:2023-12-01 17:49:37 25 4
gpt4 key购买 nike

如何为以下有效电话号码编写Java正则表达式?

有效格式:
123-456-7890,
1234567890

我在下面尝试了无效

 List phoneNumbers = new ArrayList();
//Valid phone numbers
phoneNumbers.add("1234567890");
phoneNumbers.add("123-456-7890");

//Invalid phone numbers
phoneNumbers.add("12345678");
phoneNumbers.add("(123)456-7890");

String regex = "^\\(?([0-9]{3})\\)?[-]?([0-9]{3})[-]?([0-9]{4})$";

Pattern pattern = Pattern.compile(regex);

for(String email : phoneNumbers)
{
Matcher matcher = pattern.matcher(email);
System.out.println(email +" : "+ matcher.matches());
}


我该如何实现。提前致谢。

最佳答案

仅使用两种格式,这似乎会更简单。令x为数字。


xxx,然后是-xxx-或xxx,然后是xxxx。


        Predicate<String> check =
s -> s.matches("^\\[1-9]\\d{2}((-\\d{3}-)|(\\d{3}))\\d{4}$");

List<String> phoneNumbers = new ArrayList<>(
List.of("123-456-7890", "123456789", "1234-55-888",
"1234567898", "112-", "123456689001"));

for (String phone : phoneNumbers) {
System.out.printf("%8s -> %s%n",
check.test(phone) ? "valid" : "invalid", phone);
}


版画

   valid -> 123-456-7890
invalid -> 123456789
invalid -> 1234-55-888
valid -> 1234567898
invalid -> 112-
invalid -> 123456689001

关于java - Java Regex电话号码验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60818990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com