这是我的问题:
为电话号码创建一个构造函数,给出xxx-xxx-xxxx或xxx-xxxx格式的字符串作为本地号码。如果格式无效,则抛出异常。
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.
所以我想用正则表达式验证它,但我不知道我是否正确执行。我还要扔什么样的例外?我是否需要创建自己的例外?
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 = Patternpile(expression); Matcher matcher = pattern.matcher(inputStr); if(matcher.matches()){ isValid = true; } return isValid; }对不起,是的,这是作业。对于此分配,唯一有效的格式是xxx-xxx-xxxx和xxx-xxxx,在这种情况下,所有其他格式(xxx)xxx-xxxx或xxxxxxxxxx均无效。
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.
我想知道我的正则表达式是否正确
I would like to know if my regular expression is correct
推荐答案
所以我在想使用正则表达式验证它,但我不知道我是否正确使用它。
它确实看起来过于复杂。此外,匹配 xxx-xxx-xxxx 或 xxx-xxxx 其中 x 是一个数字,可以用(\\\\ {3} - ){1,2} \\d {4}更好地完成。要了解有关正则表达式的更多信息,我建议您浏览 regular-expressions.info 。
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 regular-expressions.info.
我还要抛出什么样的异常?我是否需要创建自己的例外?
A ValidatorException 似乎很直接。
public static void isPhoneNumberValid(String phoneNumber) throws ValidatorException { if (!phoneNumber.matches(regex)) { throws ValidatorException("Invalid phone number"); } }如果您不想自己创建一个一些原因,那么我可能会选择 IllegalArgumentException ,但我仍然不建议这样做。
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.
那个说,这个验证当然不包括国际和/或外部电话号码。除非这是真正的功课,否则我建议重新考虑验证。
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.
更多推荐
java电话号码验证
发布评论