Regular Expression to validate Sri Lankan phone numbers
Here is a quick regex to validate Sri Lankan phone numbers. In addition to validation, it can capture the area code, fixed line and mobile carrier codes so you can make a thorough validation if necessary.
Regex
^(?:0|94|\+94|0094)?(?:(?P<area>11|21|23|24|25|26|27|31|32|33|34|35|36|37|38|41|45|47|51|52|54|55|57|63|65|66|67|81|91)(?P<land_carrier>0|2|3|4|5|7|9)|7(?P<mobile_carrier>0|1|2|4|5|6|7|8)\d)\d{6}$`
For regular expression engines that do not support named groups, use the one below:
^(?:0|94|\+94|0094)?(?:(11|21|23|24|25|26|27|31|32|33|34|35|36|37|38|41|45|47|51|52|54|55|57|63|65|66|67|81|91)(0|2|3|4|5|7|9)|7(0|1|2|4|5|6|7|8)\d)\d{6}$`
Explanation
This tries to forgive formatting mistakes such as the lack of 0
trunk prefix, or the 94
country code. Phone number should be either a mobile number (start with 7) or a valid area code. There are 29 area codes in use, and they are hard-coded.
If the phone number is belongs to an area code, which means this phone number is a fixed land line, we validate the next number to belong to one of the known fixed line carriers.
For mobile phone numbers, they must start with 7
, followed by the the number assigned to a list of known carrier prefixes.
Named Capture Groups
If you want to inspect the phone number more, you can use the named groups. The syntax should work in PHP and Python, but pre-ES2018 JavaScript Regex engines will need to use the second regex and pick numbered capture groups.
area
/0
: The area code. If this is captured, this means the phone number is a fixed line. See list.land_carrier
/1
: Only present for fixed lines. Fixed line carrier code. See list.mobile_carrier
/2
: Only present for mobile lines. Mobile operator carrier code. See list.
area
group will always follow a land_carrier
. area
+ land_carrier
and mobile_carrier
are mutually exclusive.
Code Examples
PHP
$regex = '/^(?:0|94|\+94)?(?:(?P<area>11|21|23|24|25|26|27|31|32|33|34|35|36|37|38|41|45|47|51|52|54|55|57|63|65|66|67|81|912)(?P<land_carrier>0|2|3|4|5|7|9)|7(?P<mobile_carrier>0|1|2|4|5|6|7|8)\d)\d{6}$/';
$input = '0777777777';
preg_match_all($regex, $input, $matches, PREG_SET_ORDER, 0);
var_dump($matches);
JavaScript
const regex = /^(?:0|94|\+94)?(?:(11|21|23|24|25|26|27|31|32|33|34|35|36|37|38|41|45|47|51|52|54|55|57|63|65|66|67|81|912)(0|2|3|4|5|7|9)|7(0|1|2|4|5|6|7|8)\d)\d{6}$/;
const input= `0777777777`;
let matches;
matches= regex.exec(input);
console.log(matches);