Home > Software design >  How to create a regex with 13 characters and exact start?
How to create a regex with 13 characters and exact start?

Time:04-05

Hello I have a problem create regular expression (phone number) for the following conditions:

  • must contain exactly 13 characters
  • must only start 421 or 420
  • only numbers must follow
  • must ignore spaces

the finally format must be: 421 xxx xxx xxx or 420 xxx xxx xxx

I've created something like this so far, but I have no idea how to proceed.

const regexPhone = /^\ [0-9]{12}/i;

Can you help me please?

CodePudding user response:

Regex patterns are often created on the basis of how the text 'looks', like in your example the numbers should look like " 420 xxx xxx xxx", so why not make regex for this exact format?

Try this: /^\ 42[10] \d{3} \d{3} \d{3}$/

let pattern = /^\ 42[10] \d{3} \d{3} \d{3}$/
let s = " 421 543 100 478"
console.log(pattern.test(s))

Now you can simplify the above regex to /^\ 42[10]( \d{3}){3}$/

^             matches the start of the string
\             matches  
42[10]        matches 42 followed by either 1 or 0
( \d{3}){3}   matches a space followed by three digits, this inturn is matched exactly three times
$             matches the end of the string
  • Related