RegEx for UK phone numbers

DreamThrall

Newbie
Joined
Oct 14, 2003
Messages
3,483
Reaction score
0
So I need to validate UK phone numbers, and based on what I found on Wikipedia's article on the UK phone number plan, this is what I've come up with:

Code:
^\(?(?<AreaCode>(?:(?<ac011>011\d)|(?<ac02>02\d)))[ \-)]?(?<TownCode>(?(ac011)\d{3})(?(ac02)\d{4}))[ \-]?(?<Number>\d{4})$

This is C#'s version of regex, so it may be a little different, so I'll translate:
  1. ^ Beginning of string
  2. \(? Optional opening parenthesis
  3. (?<AreaCode> begin named capture "AreaCode"
  4. (?: begin unnamed group
  5. (?<ac011> begin named capture "ac011" (for area codes beginning with "011")
  6. 011\d "011" followed by any digit
  7. | OR
  8. (?<ac02> begin named capture "ac02" (for area codes beginning with "02")
  9. 02\d "02" followed by any digit
  10. ) end capture/group
  11. [ \-)] optional space, dash or closing parenthesis
  12. (?<TownCode> begin capture for town code
  13. (?(ac011) if the named group "ac011" captured anything...
  14. \d{3} any digit x3
  15. ) end named capture
  16. (?(ac02) if the named capture "02" captured anything
  17. \d{4} any digit x4
  18. ) end capture
  19. $ end of string

So basically:
(011x) xxx xxxx OR
(02x) xxxx xxxx
with the parenthesis being optional, and the spaces being optional or replaced by dashes

Any comments?

EDIT: Oh yeah, the answer is "yes", my powers of RegEx are godly. :D
 
I'm planning a massive effort to stalk all UK-based HL.net membersNobody... My company is localizing one of our websites, we need to be able to validate UK addresses and phone numbers :)
 
Back
Top