"Cleaner" Method of Regex Matching Character(s) Only If Other(s) is/are Present - Build a Telephone Number Validator

Hey everyone :wave:

I’m working on the Build a Telephone Number Validator project, and I came up with this regex to match valid US phone number formatting (with some kind help from the fCC forum):

const phoneRegex = /^1? ?(\(\d{3}\)|\d{3})( |-)?\d{3}( |-)?\d{4}$/;

The part

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

matches three digits either alone or with both an opening paranthesis before them and a closing paranthesis after them.

This part (with the right anchors) would match 123 or (123) but not (123 or 123).

I’m wondering if there’s a “cleaner” (i.e. more efficient and generally applicable) way of achieving the same result: making a regex match a certain character or group of characters only if another character or group of characters is present.

Thank you!

sounds like you need to research ‘regex lookaheads or lookbehinds’
it is not covered in the curriculum right now.

1 Like

Good to know. Thanks!

1 Like