简体   繁体   English

java电话号码验证

[英]java phone number validation

Here is my problem: 这是我的问题:

Create a constructor for a telephone number given a string in the form xxx-xxx-xxxx or xxx-xxxx for a local number. 为给定字符串的电话号码创建一个构造函数,其形式为xxx-xxx-xxxx或xxx-xxxx,表示本地号码。 Throw an exception if the format is not valid. 如果格式无效,则抛出异常。

So I was thinking to validate it using a regular expression, but I don't know if I'm doing it correctly. 所以我想用正则表达式验证它,但我不知道我是否正确地做了。 Also what kind of exception would I have to throw? 我还要扔什么样的例外? Do I need to create my own exception? 我需要创建自己的例外吗?

    public TelephoneNumber(String aString){
        if(isPhoneNumberValid(aString)==true){
            StringTokenizer tokens = new StringTokenizer("-");
            if(tokens.countTokens()==3){
                areaCode = Integer.parseInt(tokens.nextToken());
                exchangeCode = Integer.parseInt(tokens.nextToken());
                number = Integer.parseInt(tokens.nextToken());
            }
            else if(tokens.countTokens()==2){
                exchangeCode = Integer.parseInt(tokens.nextToken());
                number = Integer.parseInt(tokens.nextToken());
            }
            else{
                //throw an excemption here
            }
        }

    }


 public static boolean isPhoneNumberValid(String phoneNumber){
     boolean isValid = false;

     //Initialize reg ex for phone number.
    String expression = "(\\d{3})(\\[-])(\\d{4})$";
    CharSequence inputStr = phoneNumber;
    Pattern pattern = Pattern.compile(expression);
    Matcher matcher = pattern.matcher(inputStr);
    if(matcher.matches()){
        isValid = true;
     }
        return isValid;
    }

Hi sorry, yes this is homework. 对不起,是的,这是功课。 For this assignments the only valid format are xxx-xxx-xxxx and xxx-xxxx, all other formats (xxx)xxx-xxxx or xxxxxxxxxx are invalid in this case. 对于此分配,唯一有效的格式是xxx-xxx-xxxx和xxx-xxxx,在这种情况下,所有其他格式(xxx)xxx-xxxx或xxxxxxxxxx均无效。

I would like to know if my regular expression is correct 我想知道我的正则表达式是否正确

So I was thinking to validate it using a regular expression, but I don't know if I'm doing it correctly. 所以我想用正则表达式验证它,但我不知道我是否正确地做了。

It indeed looks overcomplicated. 它确实看起来过于复杂。 Also, matching xxx-xxx-xxxx or xxx-xxxx where x is a digit can be done better with "(\\\\d{3}-){1,2}\\\\d{4}" . 此外,匹配xxx-xxx-xxxxxxx-xxxx ,其中x是数字,可以使用"(\\\\d{3}-){1,2}\\\\d{4}"更好地完成。 To learn more about regex I recommend to go through http://regular-expressions.info . 要了解有关正则表达式的更多信息,我建议您浏览http://regular-expressions.info

Also what kind of exception would I have to throw? 我还要扔什么样的例外? Do I need to create my own exception? 我需要创建自己的例外吗?

A ValidatorException seems straight forward. ValidatorException似乎很简单。

public static void isPhoneNumberValid(String phoneNumber) throws ValidatorException {
    if (!phoneNumber.matches(regex)) {
        throws ValidatorException("Invalid phone number");
    }
}

If you don't want to create one yourself for some reasons, then I'd probably pick IllegalArgumentException , but still, I don't recommend that. 如果由于某些原因你不想自己创建一个,那么我可能会选择IllegalArgumentException ,但我仍然不建议这样做。

That said, this validation of course doesn't cover international and/or external telephone numbers. 也就是说,此验证当然不包括国际和/或外部电话号码。 Unless this is really homework, I'd suggest to rethink the validation. 除非这是真正的功课,否则我建议重新考虑验证。

^(([(]?(\d{2,4})[)]?)|(\d{2,4})|([+1-9]+\d{1,2}))?[-\s]?(\d{2,3})?[-\s]?((\d{7,8})|(\d{3,4}[-\s]\d{3,4}))$

matches: (0060)123-12345678, (0060)12312345678, (832)123-1234567, (006)03-12345678, 匹配:(0060)123-12345678,(0060)12312345678,(832)123-1234567,(006)03-12345678,

(006)03-12345678, 00603-12345678, 0060312345678 (006)03-12345678,00603-12345678,0060312345678

0000-123-12345678, 0000-12-12345678, 0000-1212345678 ... etc. 0000-123-12345678,0000-12-12345678,0000-1212345678 ......等

1234-5678, 01-123-4567 1234-5678,01-123-4567

Can replace '-' with SPACE ie (0080) 123 12345678 可以用SPACE替换' - ',即(0080)123 12345678

Also matches +82-123-1234567, +82 123 1234567, +800 01 12345678 ... etc. 也符合+ 82-123-1234567,+ 82 123 1234567,+ 800 01 12345678等。

More for house-hold/private number. 更多关于家庭/私人号码。 Not for 1-800-000-0000 type of number 不适用于1-800-000-0000类型的号码

*Tested with Regex tester http://regexpal.com/ *使用Regex测试仪进行测试http://regexpal.com/

You could match those patterns pretty easily as suggested by BalusC. 您可以像BalusC建议的那样轻松匹配这些模式。

As a side note, StringTokenizer has been deprecated. 作为旁注, StringTokenizer已被弃用。 From JavaDoc : 来自JavaDoc

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. StringTokenizer是一个遗留类,出于兼容性原因而保留,尽管在新代码中不鼓励使用它。 It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead. 建议任何寻求此功能的人都使用String的split方法或java.util.regex包。

An easier way to split your string into the appropriate segments would be: 将字符串拆分为适当段的更简单方法是:

String phoneParts[] = phoneNumber.split("-");

String pincode = "589877"; String pincode =“589877”;

    Pattern pattern = Pattern.compile("\\d{6}");

\\d indicates the digits. \\ d表示数字。 inside the braces the number of digits Matcher matcher = pattern.matcher(pincode); 在大括号内,Matcher matcher = pattern.matcher(pincode)的位数;

    if (matcher.matches()) {
        System.out.println("Pincode is Valid");
        return true;
    } else {
        System.out.println("pincode must be a 6 digit Number");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM