中的电话号码验证

中的电话号码验证

本文介绍了Java 中的电话号码验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码来验证电话号码.要求电话号码长度在10-25个字符之间,包括连字符(-)、句号(.)、括号().

I am using the following code to validate a phone number. The requirements are the phone number should be inbetween 10-25 characters length, should include hypen(-),period(.), parentheses ().

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class ValidatePhoneNumber {

public static void main(String[] argv) {

    String phoneNumber = "6058.8()6-05888,9994567";
    System.out.println(phoneNumber.length());
    //String sPhoneNumber = "605-88899991";
    //String sPhoneNumber = "605-888999A";
    String regex = "^[0-9.()-]{10,25}$";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(phoneNumber);

    if (matcher.matches()) {
        System.out.println("Phone Number Valid");
    } else {
        System.out.println("Phone Number must be in the form XXX-XXXXXXX");
    }
  }
 }

我检查了验证及其工作正常,我还想添加一个空格字符\s",以便在电话号码之间也可以有空格.但是在正则表达式中添加\s"时出错.

I checked the validations and its working fine, I want to add a whitespace character "\s" as well so that in between the phone number there can be whitespace as well. But getting errors while adding "\s" in regex.

推荐答案

请查看 ITU E.164 或 IETF RfC 3966 等标准.不要假设每个国家/地区都有相同的约定和号码长度.

Please, look at standards like ITU E.164 or IETF RfC 3966. Don't assume that every country has the same conventions and number lengths.

这是 RfC 3966 中相关的 ABNF 部分

Here's the relevant ABNF part out of RfC 3966

global-number-digits = "+" *phonedigit DIGIT *phonedigit
phonedigit           = DIGIT / visual-separator
visual-separator     = "-" / "." / "(" / ")"
DIGIT = "0" / "1" / "2" / "3" / "4" / "5" / "6" / "7" / "8" / "9"

我们最近在一个设备上遇到了一个大问题,该设备不允许用户在电话号码中输入+".

We recently had a huge trouble with a device that didn't let the user enter the '+' as part of a phone number.

这篇关于Java 中的电话号码验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 16:18