Hey everyone
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!