Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I tried below regex for phone numbers validation but did not work properly,

^([+61|0](2|4|3|7|8|)){0,2}([ 0-9]|[(]){2,3}([)]|[0-9]){6}([ ])[0-9]{7,20}$

Here are examples I expect to pass validation

+61(02)89876544
+61 2 8986 6544
02 8986 6544
+61289876544
0414 570776 
0414570776
0414 570 776
+61 414 570776
+61 (0)414 570776

below characters also be accepted. ()-+ space

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
396 views
Welcome To Ask or Share your Answers For Others

1 Answer

That's quite the phone number structure. The easiest solution is to ask the user to input in a particular format or have the the form automatically format it. If you must use a regex, this is what I came up with:

^(?:+?(61))? ?(?:((?=.*)))?(0?[2-57-8]))? ?(dd(?:[- ](?=d{3})|(?!dd[- ]?d[- ]))dd[- ]?d[- ]?d{3})$

Capture groups:

  1. Country Code (optional)
  2. Area/Provider Code (optional)
  3. The Phone Number

Demo: https://regex101.com/r/dkFASs/6

This was what I used to nail down the format: https://en.wikipedia.org/wiki/Telephone_numbers_in_Australia

When tackling a larger regex like this, I find the esiest way is to stick your test cases into a tool like regex101.com and then go capture group by capture group (naming them if you can) until you get to the end. As soon as one group doesn't match, change what you already have until it does.

Edit 2019: Since this question still gets attention occasionally, I wanted to note that it might be better to use a validation library if possible. My suggestion would be Google's i18n library for phone numbers. It's much more robust than a regex could ever be.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...