Become a fan
Twitter
Home

Regular expression for Belgian phone numbers

Author Joseph Stenhouse on November 27, 2010 | | |


I needed a regular expression to parse Belgian phone numbers for a program I am writing. At first sight regular expressions can be quite difficult for people to understand. Luckily I have a course at University that studies the mathematics behind regular expressions and the languages they define. A lovely exercise.

Belgian phone numbers comply with following specifications:

    * The 2 possible formats are 01 234 56 78 and 012 34 56 78.
    * The first 2 or 3 digits, the zone number, always start with a zero.
    * The entire phone numer counts 9 digits.

There exist multiple other notations such as 012/34.56.78 and 012/34.56.78. The strenght of a regular expression is that it can describe all these notations in one line. This easy regular expression will do the necessary, though will also accept 10 digit numbers:

[0](?:\\d{1,2})[/. ]?(?:\\d{2,3})[. ]?(?:\\d{2})[. ]?(?:\\d{2})

[0](?:\\d{1})[/. ]?(?:\\d{3})[. ]?(?:\\d{2})[. ]?(?:\\d{2})|[0](?:\\d{2})[/. ]?(?:\\d{2})[. ]?(?:\\d{2})[. ]?(?:\\d{2})

Belgian cell phone numbers on the other hand have a slightly different format so another expression is necessary:

    * The used format is 0412 34 56 67
    * The first 2 digits should always start with 04
    * The total number of digits should always be 10

Again multiple notations exist to write down cell phone numbers. An expression that only accepts this format with the most commonly used notations is:

[0][4](?:\\d{2})[/. ]?(?:\\d{2,3})[. ]?(?:\\d{2})[. ]?(?:\\d{2})

A small program in java that uses these regular expressions could look like:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class PhoneNumberValidator {
// Check for valid Belgian phone numbers
public static boolean isValidPhoneNumber(String input) {
Pattern p = Pattern.compile("[0](?:\\d{1,2})[/. ]?(?:\\d{2,3})[. ]?(?:\\d{2})[. ]?(?:\\d{2})");
Matcher m = p.matcher(input);
return m.matches();
}
// Check for valid Belgian cell phone numbers
public static boolean isValidCellPhoneNumber(String input) {
Pattern p = Pattern.compile("[0][4](?:\\d{2})[/. ]?(?:\\d{2,3})[. ]?(?:\\d{2})[. ]?(?:\\d{2})");
Matcher m = p.matcher(input);
return m.matches();
}
}

Was this article helpful?

Yes No

Category: Java

Last updated on November 29, 2010 with 1035 views