DEV Community

Philip Mutua
Philip Mutua

Posted on • Edited on

5 4

Regex for Kenyan Phone Number format 07XXXXXXXX in Python

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 ;)

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay