Skip to content
Advertisement

Reject optional whitespaces after area code and before local number (US)

I have a regex that parses US phone numbers into 3 strings.

JavaScript

it works perfectly on the numbers:

JavaScript

Now I need to add an additional regex to generate a Value Error for numbers such as

JavaScript

I tried

JavaScript

but non rejects the string in question

I will greatly appreciate any ideas. I am very new to Regex!

Advertisement

Answer

In Python re you could use a conditional to check for group 1 having the opening parenthesis.

If that is the case match the closing parenthesis, optional spaces and 3 digits. Else match - and 3 digits.

If you use re.match you can omit ^

JavaScript

If you want to match the whole string and trailing whitespace chars:

JavaScript

In parts, the pattern matches:

  • ^ Start of string
  • s* Match optional whitespace chars
  • (()? Optional group 1, match (
  • d+ Match 1+ digits
  • (? Conditional
    • (1))s*d{3} If group 1 exist, match the closing ), optional whitespace chars and 3 digits
    • | Or
    • -? Match optional –
    • d{3} Match 3 digits
  • ) close conditional
  • -?d{4} Match optional – and 4 digits

See a regex demo

For example, using capture groups in the pattern to get the digits:

JavaScript

Output

JavaScript

Python demo

Advertisement