1

I'd like to know how can I match text ONLY if there are both parentheses (starting and closing).

Currently, my RegExp is: ^1?\s?\(?\d{3}\)?[-\s]?\d{3}[-\s]?\d{4}$.

It checks for US valid numbers, however \(? and \)? makes the difference. It should match the text if there is 0 of them or 2.


Some tests:

1 555)555-5555 - false

555)-555-5555 - false

(555-555-5555 - false

Now, they all return the same result - true.


Here is the link to it: https://regexr.com/3kjei (^ is because I have to select only one string without any line break, please remove 2 other strings from it so you can see it returns true. All of the strings in this link should return true, just check it so only one string is in the text editor).

Thank you

2 Answers2

1

You may use

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

See the regex demo.

Note that ^1?\s? in your regex allow a single whitespace in the beginning, that is why I suggest ^(?:1\s?)? - an optional sequence starting with 1 that is optionally followed wih whitespace.

The \(?\d{3}\)? part is replaced with (?:\(\d{3}\)|\d{3}) - a non-capturing group that matches either (+3 digits+) or 3 digits (so, no (123 or 123)` can be matched).

Details

  • ^ - start of string
  • (?:1\s?)? - 1 or 0 occurrences of 1 optionally followed with 1 whitespace char
  • (?:\(\d{3}\)|\d{3}) - either (, 3 digits, ) or just 3 digits
  • [-\s]? - an optional - or whitespace
  • \d{3} - 3 digits
  • [-\s]?- an optional - or whitespace
  • \d{4} - 4 digits
  • $ - end of string.
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
1

Why not in the portion of your regex that says \(?\d{3}\)? that you "or" it instead. Eg. Replace it with something like this:

((\(\d{3}\))|\d{3})

Adel Helal
  • 522
  • 1
  • 7
  • 18