Although I have used regular expressions fairly often, I rarely create my own. I've been reading up on them recently as I need to create some fairly specific expressions for a project I am working on.
I have a very specific brief as to which telephone numbers are allowed in a form. There are restrictions on either the first two or else the first three numbers.
Numbers must start with 06 or 07, or alternatively with 081, 082, 083 or 084.
I have written a regular expression with a conditional statement that I believe should do one of two things:
- If the number starts with
06or07, then check that the other 8 characters in the string are numbers. - If the number starts with
08, check that the next character is between1and4, then check that the other 7 characters are numbers.
I used this tutorial to learn how conditionals work in regex. Here is the expression that I created:
const validMobile = new RegExp(/^((0)?([6-7])[0-9]{8}|([8])[1-4][0-9]{7}) *$/);
What I understand here is as follows:
/^(Starts with)(0)(must have a zero first)?([6*7])(if the second character is six or seven)[0-9]{8}(check that the next eight characters are numbers between zero and 9)|(8)(else if the second character is eight)[1-4](check that the third character is a number between one and four)[0-9]{7}(check that the following seven characters are numbers between zero and nine)
Note that the length of the string is being checked elsewhere, although I think this expression should also facilitate a check that the number is exactly 10 characters long.
This is not delivering the expected result, so I must be misunderstanding something. Could anyone please help me understand where I might be going wrong?