Regular expression for Belgian phone numbers
I needed a regular expression for Belgian phone numbers for a program I am writing. At first sight regular expressions can be quite difficult for people to understand but luckily I have a course at University that studies the mathematics behind regular expressions and the languages they define. A nice but easy exercise.
Belgian phone numbers have the following format: 01 234 56 78 or 012 34 56 78. The first 3 digits, the zone number, always starts with a zero. The total numbers of zeros should always be 9. There exist multiple other notations like 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}). You could however use a logical or between two expressions to make sure only 9 digit phone numbers are accepted: [0](?:\\d{1})[/. ]?(?:\\d{3})[/. ]?(?:\\d{2})[/. ]?(?:\\d{2})|[0](?:\\d{2})[/. ]?(?:\\d{2})[/. ]?(?:\\d{2})[/. ]?(?:\\d{2})
Belgian cellular phones 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 cellular phone numbers. An expression that only accepts this format with the commonly used notations is: 0][4](?:\\d{2})[/. ]?(?:\\d{2,3})[/. ]?(?:\\d{2})[/. ]?(?:\\d{2})
A small program in java that uses this regular expressions could look like:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class InputValidator { // 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(); } }
Hi, I’m looking for a regular expression like that, but without any spaces or characters between the numbers. I’m not that good at regular expressions, I tried to remove the “[/. ]?” sections but it doesn’t seem to work :-/. Any suggestions ?
If I remove the [/. ]? sections from the expression, it works over here. This would be the RE:
[0](?:\\d{1,2})?(?:\\d{2,3})(?:\\d{2})(?:\\d{2})
Perhaps you can give yours and an example of a phone number that fails?
I did this and it seems to be working ^[0]([1-9])([0-9]){7}$, maybe it’s not as accurate as yours ?
Since you wanted to trim out the spaces or dots, it can indeed be simplified to your version.