0

I have to write a regular expression to match phone numbers. A phone number can be in any one of the following forms:

(123) 456-7890
(123)456-7890
1234567890
123 456 7890
123-456-7890
123.456.7890

I have to store the regular expression in a variable called re5.

The test cases I have to pass are here: link

I just need the re5 = "..." part, where I need the correct code for the ... part.

This is what I have so far..

re5 = "^(\\d{3}|\\(\\d{3}\\))([ ]?\\d{3}[-]|[ ]\\".

I don't know what is going wrong. Thanks!

Different that other answers due to test cases in link above.

stevie kay
  • 53
  • 1
  • 6

1 Answers1

0

This passes all your tests:

^(?:\(\d{3}\)|\d{3})(?: |([-.])?)\d{3}(?(1)\1|[ -.]?)\d{4}$

Bear in mind that this uses PCRE-specific syntax, so you'll need to enable that using perl = TRUE

squirl
  • 1,636
  • 1
  • 16
  • 30