开发者

Regex - simple phone number

I know there are a ton of regex examples on how to match certain phone number types. For my example I just want to allow numbers and a few special characters. I am again having trouble achieving this.

Phone numbers that should be allowed could take these forms

5555555555
555-555-5555
(555)5555555
(555)-555-5555
(555)555-5555 and so on

I just want something that will allow [0-9] and also special characters '(' , ')', and '-'

so far my expression looks like this

/^[0-9]*^[()-]*$/

I know this is wrong but logically I believe this means allow numbers 0-9 or and allow ch开发者_JAVA技巧aracters (, ), and -.


^(\(\d{3}\)|\d{3})-?\d{3}-?\d{4}$
  • \(\d{3}\)|\d{3} three digits with or without () - The simpler regex would be \(?\d{3}\)? but that would allow (555-5555555 and 555)5555555 etc.
  • An optional - followed by three digits
  • An optional - followed by four digits

Note that this would still allow 555555-5555 and 555-5555555 - I don't know if these are covered in your and so on part


This match what you want numbers,(, ) and -

/^[0-9()-]+$/


^[0-9-+\s]+$


06754654 +54654654 +546 546 5654 43534 + +09945 345 3453 45


Why do you have a stray ^ in there? I think you meant [()-] This is actually making you have to have two beginning-of-strings in the regex, which will never match.

Also, \d is a nice shortcut for [0-9]. They are exactly the same.

Also, this will only match a bunch of numbers, then a bunch of ( or ) or -. Something like: 1294819024()()()()()-----()- would match. I think you want the whole thing to be able to repeat, something like: ^(\d*[()-]*)*$. Now, you can match repeating sequences of this.

Now, it is important to notice that nested * are typically inefficient, we can realize that we are just wanting to match any digit and the punctuation you want: [\d()-]*


For digits you can use \d. For more than one digit, you can use \d{n}, where n is the number of digits you want to match. Some special characters must be escaped, for example \( matches (. For example: \(\d{3}\)\-\d{3}\-\d{4} matches (555)-555-5555.


The second carat (afaik) is going to break anything you do since it means "start of string".

What you appear to be asking for therefore is:

  • start of string, followed by...
  • any number of numeric characters, followed by...
  • start of string, followed by...
  • any number of '(',')', or '-' characters, followed by...
  • end of string

Which won't work even if that second carat does nothing, because you're not accounting for anything after the first '(',')', or '-', and in fact will probably only validate an empty string if that.

You want /^[0-9()-]+$/ for a very crude pattern which will "work".


If you are doing US only number the best solution is to strip out all the non-digit characters and then just test to see if the length == 10.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜