Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for UK Mobile Number - Python

I need a regular expression that only validates UK mobile numbers.

A UK mobile number can be between 10-14 digits and either starts with 07, or omits the 0 and starts with 447.

Importantly, if the user adds +44 it should be rejected.

So these would be valid:

07111111111

447111111111

and these would be invalid:

+4471111111111

021929182711

00701029182


What I have so far:

rule = re.compile(r'^\+?(44)?(0|7)\d{9,13}$')

if not rule.search(value):
    msg = u"Invalid mobile number."
    raise ValidationError(msg)

This does not validate according to my rules yet; could someone help?

like image 258
GrantU Avatar asked May 06 '13 18:05

GrantU


People also ask

How can I check mobile number in regex?

/^([+]\d{2})? \d{10}$/ This is how this regex for mobile number is working. + sign is used for world wide matching of number.


2 Answers

The following regex seems like it would fit your requirements, if I understand them correctly.

Not allowing a + sign is very easy as you're only creating a whitelist of values, and the plus isn't among them.

^(07[\d]{8,12}|447[\d]{7,11})$

As was mentioned in the comments for this answer, the square brackets are not necessary here. I included them to make my own reading of this regex a little easier on my eyes. However, the following works just as well:

^(07\d{8,12}|447\d{7,11})$

like image 72
BlackVegetable Avatar answered Sep 25 '22 17:09

BlackVegetable


I had a play around with @BlackVegetable's answer for a pattern for UK numbers and this works for me (07\d{9}|447\d{9})$

Note that this pattern only accounts for UK mobile numbers that are 11 digits in length.

like image 37
michael bishop Avatar answered Sep 25 '22 17:09

michael bishop