java中的电话号码验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27631692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 04:44:45  来源:igfitidea点击:

phone Number validation in java

javaregexvalidation

提问by Devendra

I want to validate a phone number in such Way :-

我想以这种方式验证电话号码:-

The field should allow the user to enter characters and should auto-correct. So an entry of "+1-908-528-5656" would not create an error for the user, it would just change to "19085285656".

该字段应允许用户输入字符并应自动更正。因此,输入“+1-908-528-5656”不会为用户创建错误,它只会更改为“19085285656”。

I also want to number range between 9 to 11.

我也想编号范围在 9 到 11 之间。

I also tried with the below code but not concluded to the final solution:

我也尝试了下面的代码,但没有得出最终的解决方案:

 final String PHONE_REGEX = "^\+([0-9\-]?){9,11}[0-9]$";
 final Pattern pattern = Pattern.compile(PHONE_REGEX);
 String phone = "+1-908-528-5656";      
 phone=phone.replaceAll("[\-\+]", "");
 System.out.println(phone);
 final Matcher matcher = pattern.matcher(phone);
 System.out.println(matcher.matches()); 

采纳答案by Braj

You can use simple String.matches(regex)to test any string against a regex pattern instead of using Patternand Matcherclasses.

您可以使用 simpleString.matches(regex)来针对正则表达式模式测试任何字符串,而不是使用PatternMatcher类。

Sample:

样本:

boolean isValid = phoneString.matches(regexPattern);

Find more examples

查找更多示例

Here is the regex pattern as per your input string:

这是根据您的输入字符串的正则表达式模式:

\+\d(-\d{3}){2}-\d{4}

Online demo

在线演示



Better use Spring validation annotationfor validation.

最好使用Spring 验证注解进行验证。

Example

例子

回答by k_g

Assuming you want an optimization (which is what your comment suggests).

假设您想要优化(这就是您的评论所建议的)。

How bout this? (the "0" is to exclude if they give complete garbage without even a single digit).

这个怎么样?(“0”是排除如果他们给出完整的垃圾,甚至没有一个数字)。

 int parse(String phone){
     int num = Integer.parseInt("0"+phone.replaceAll("[^0-9]",""));
     return 100000000<=num&&num<100000000000?num:-1;
 }

回答by Md. kamrul Hasan

Assuming your input field take any kind of character and you just want the digits.

假设您的输入字段采用任何类型的字符,而您只需要数字。

 String phone = "+1-908-528-5656";
 phone=phone.replaceAll("[\D]","");
 if(phone.length()>=9 || phone.length()<=11)
   System.out.println(phone);

回答by Deepak

I am not sure but removing the garbage characters parenthesis, spaces and hyphens, if you match with ^((\+[1-9]?[0-9])|0)?[7-9][0-9]{9}$ , you may validate a mobile number

我不确定但删除垃圾字符括号、空格和连字符,如果你匹配^((\+[1-9]?[0-9])|0)?[7-9][0-9] {9}$,您可以验证手机号码

private static final String PHONE_NUMBER_GARBAGE_REGEX = "[()\s-]+";
private static final String PHONE_NUMBER_REGEX = "^((\+[1-9]?[0-9])|0)?[7-9][0-9]{9}$";
private static final Pattern PHONE_NUMBER_PATTERN = Pattern.compile(PHONE_NUMBER_REGEX);

public static boolean validatePhoneNumber(String phoneNumber) {
    return phoneNumber != null && PHONE_NUMBER_PATTERN.matcher(phoneNumber.replaceAll(PHONE_NUMBER_GARBAGE_REGEX, "")).matches();
}

回答by rohan

We can use String.matches(String regex)1to validate phone numbers using java.

我们可以使用String.matches(String regex)1来验证使用 java 的电话号码。

Sample code snippet

示例代码片段

package regex;

public class Phone {
    private static boolean isValid(String s) {
        String regex = "\d{3}-\d{3}-\d{4}"; // XXX-XXX-XXXX
        return s.matches(regex);
    }

    public static void main(String[] args) {
        System.out.println(isValid("123-456-7890"));
    }

}

P.S. The regex pattern we use extra '\' for escaping when we use in java string. (Try to use "\d{3}-\d{3}-\d{4}" in java program, you will get an error.

PS 当我们在 java 字符串中使用时,我们使用额外的 '\' 进行转义的正则表达式模式。(在java程序中尝试使用“\d{3}-\d{3}-\d{4}”,会报错。

回答by jessica

// The Regex not validate mobile number, which is in internation format.
// The Following code work for me. 
// I have use libphonenumber library to validate Number from below link.
// http://repo1.maven.org/maven2/com/googlecode/libphonenumber/libphonenumber/8.0.1/
//  https://github.com/googlei18n/libphonenumber
// Here, is my source code.

 public boolean isMobileNumberValid(String phoneNumber)
    {
        boolean isValid = false;

        // Use the libphonenumber library to validate Number
        PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
        Phonenumber.PhoneNumber swissNumberProto =null ;
        try {
            swissNumberProto = phoneUtil.parse(phoneNumber, "CH");
        } catch (NumberParseException e) {
            System.err.println("NumberParseException was thrown: " + e.toString());
        }

        if(phoneUtil.isValidNumber(swissNumberProto))
        {
            isValid = true;
        }

        // The Library failed to validate number if it contains - sign
        // thus use regex to validate Mobile Number.
        String regex = "[0-9*#+() -]*";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(phoneNumber);

        if (matcher.matches()) {
            isValid = true;
        }
        return isValid;
    }

回答by Armer B.

One easy and simple to use java phone validation regex:

一个简单易用的 java 手机验证正则表达式:

public static final String PHONE_VERIFICATION = "^[+0-9-\(\)\s]*{6,14}$";

private static Pattern p;
private static Matcher m;

public static void main(String[] args)
{
    //Phone validation
    p = Pattern.compile(PHONE_VERIFICATION);
    m = p.matcher("+1 212-788-8609");
    boolean isPhoneValid = m.matches();

    if(!isPhoneValid)
    {
        System.out.println("The Phone number is NOT valid!");
        return;
    }
    System.out.println("The Phone number is valid!");
}

回答by Deepesh Jain

i have done testing one regex for this combination of phone numbers

我已经为这种电话号码组合测试了一个正则表达式

(294) 784-4554
(247) 784 4554
(124)-784 4783 
(124)-784-4783
(124) 784-4783
+1(202)555-0138

THIS REGEX SURELY WILL BE WORKING FOR ALL THE US NUMBERS

这个正则表达式肯定适用于所有美国号码

\d{10}|(?:\d{3}-){2}\d{4}|\(\d{3}\)\d{3}-?\d{4}|\(\d{3}\)-\d{3}-?\d{4}|\(\d{3}\) \d{3} ?\d{4}|\(\d{3}\)-\d{3} ?\d{4}|\(\d{3}\) \d{3}-?\d{4}