Expression |
^\(?(?:(?:0(?:0|11)\)?[\s-]?\(?|\+)44\)?[\s-]?\(?(?:0\)?[\s-]?\(?)?|0)(?:\d{2}\)?[\s-]?\d{4}[\s-]?\d{4}|\d{3}\)?[\s-]?\d{3}[\s-]?\d{3,4}|\d{4}\)?[\s-]?(?:\d{5}|\d{3}[\s-]?\d{3})|\d{5}\)?[\s-]?\d{4,5}|8(?:00[\s-]?11[\s-]?11|45[\s-]?46[\s-]?4\d))(?:(?:[\s-]?(?:x|ext\.?\s?|\#)\d+)?)$
|
Description |
Step 1: Test that the input is a UK phone number. Later patterns extract the prefix, NSN and extension, and further tests check the NSN for length and validity.
The above pattern matches optional opening parentheses, followed by 00 or 011 and optional closing parentheses, followed by an optional space or hyphen, followed by optional opening parentheses. Alternatively, the opening parentheses are followed by a literal + without a following space or hyphen. Any of the previous options are then followed by 44 with optional closing parentheses, followed by optional space or hyphen, followed by optional 0 in optional parentheses, followed by optional space or hyphen, followed by optional opening parentheses (international format). Alternatively, the pattern matches optional opening parentheses followed by the 0 trunk code (national format).
This is followed by the area code and phone number in 2+8, 3+7, 3+6, 4+6, 4+5, 5+5 or 5+4 format with or without spaces and/or hyphens. This also includes provision for optional closing parentheses and/or optional space or hyphen after where the user thinks the area code ends and the local number begins. The pattern allows any format to be used with any UK number. The display format must be corrected by later logic if the wrong format for this number has been used by the user on input.
The pattern finally ends with optional space or hyphen followed by x, ext and optional period, or #, followed by a three or four digit extension number.
Once the input has been confirmed as being a telephone number using the above pattern, another RegEx pattern should extract prefix, NSN and extension and then the NSN should be further tested for length and validity.
(Order fixed for even greater efficiency: shorter area codes match first.) |
Matches |
020 3000 5555, (020) 3000 5555, +44 20 3000 5555, 00 44 20 3000 5555, 011 44 20 3000 5555, 0203 000 5555, 02030 005 555, (+44) 20 3000 5555, (+44 20) 3000 5555, and many others, any with NSN of 10 or 9. |