Regex for Kenyan Phone Number format
The common formats that people use to represent mobile phone numbers: 07xxxxxxxx
, +2547xxxxxxxx
or +2547xxxxxxxx
or 7xxxxxxxx
.
In this tutorial I will show you how to check a phone number matches in the following format 07xxxxxxxx
We are going to import re
Python module to achieve this.
import re
The we define the regular expression pattern that will check if the phone number matches. The Pattern is normally a string.
pattern = "^0(7(?:(?:[129][0-9])|(?:0[0-8])|(4[0-1]))[0-9]{6})$"
That's it we have the pattern defined.
Then we are going to define our matched variable. phone_number
variable is the number we want to check if it matches.
phone_number = "0700000000"
We are using the re.match()
function which checks if zero or more characters at the beginning of string match the regular expression pattern, returns a corresponding match object. Then returns None
if the string does not match the pattern.
matched = re.match(pattern,phone_number)
Now let's check
is_match = bool(matched)
This will return a boolean True
And there you go ;)
Top comments (0)