java电话号码验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2555182/
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
java phone number validation
提问by user69514
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. Throw an exception if the format is not valid.
为电话号码创建一个构造函数,为本地号码提供 xxx-xxx-xxxx 或 xxx-xxxx 形式的字符串。如果格式无效,则抛出异常。
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
我想知道我的正则表达式是否正确
采纳答案by BalusC
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}"
. To learn more about regex I recommend to go through http://regular-expressions.info.
它确实看起来过于复杂。此外,匹配xxx-xxx-xxxx
或数字xxx-xxxx
在哪里x
可以使用"(\\d{3}-){1,2}\\d{4}"
. 要了解有关正则表达式的更多信息,我建议访问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.
AValidatorException
似乎很直接。
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.
也就是说,这种验证当然不包括国际和/或外部电话号码。除非这真的是家庭作业,否则我建议重新考虑验证。
回答by Haldean Brown
You could match those patterns pretty easily as suggested by BalusC.
您可以按照 BalusC 的建议轻松匹配这些模式。
As a side note, StringTokenizer
has been deprecated. From JavaDoc:
作为旁注,StringTokenizer
已被弃用。从JavaDoc:
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
StringTokenizer 是一个遗留类,出于兼容性原因保留,但不鼓励在新代码中使用它。建议任何寻求此功能的人改用 String 的 split 方法或 java.util.regex 包。
An easier way to split your string into the appropriate segments would be:
将字符串拆分为适当段的更简单方法是:
String phoneParts[] = phoneNumber.split("-");
回答by peterong
^(([(]?(\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 i.e (0080) 123 12345678
可以用空格替换“-”,即 (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 类型的号码
回答by user2428282
String pincode = "589877";
字符串密码 = "589877";
Pattern pattern = Pattern.compile("\d{6}");
\d indicates the digits. inside the braces the number of digits Matcher matcher = pattern.matcher(pincode);
\d 表示数字。大括号内的位数 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");