Regex - when to use ( ) or [ ]?

I have been working on the US telephone number validator challenge and I have passed all the tests with my regex
/^(1\s?)?(\(\d{3}\)[\s\-]?|\d{3}[\s\-]?)\d{3}[\s\-]?\d{4}$/

Please could someone give me an explanation for the difference between ( ) and [ ] ?

For example, I don’t understand why it’s necessary to use (1\s?)? in parentheses but [\s\-]? in square brackets.

I know that parentheses are for groups and square brackets are for ranges but I don’t understand what this means in practical terms.

Any help appreciated!

[] defines a character set, so any character in the character set can be matched. () defines a capturing group, so you can think of it like a word.

For example, [dog] will match any d, o or g, but (dog) will match only if the word dog is found.

Checkout this site https://regexr.com/, you can see everything your regex is doing.

2 Likes

Thanks for your reply, it helps :slight_smile:

Parentheses store the match inside of them, which you can later use, for example with replace, by using the variables (i guess they are variables) $1, $2, etc. Depending on the order.

For example:

‘funny-stuff’.replace(/(funny)-/, ‘$1_’);

Here we look for funny-, and you would say, why not just look for ‘-’? Well, a hyphen is a pretty common character, so there may be more than one, and we particularly want the one following the word funny. So we look for funny-, and wrap funny with parentheses. Now we can replace the hypen with an underscore, but to preserve the word funny, by using $1. Notice we use it inside of the string.

This is not a good example. There are things like lookaheads and lookbehinds, but i promise you, i couldn’t think of a better example :grin:

Also, if you use Visual Studio Code as your text editor, if you press ctrl (or command for Mac users, i think) + f, to find some text, you can use regexp, which is pretty neat! And there i use quite a bit the kind of regexp i used for this example. So it is useful!

Hey thanks Manu this is great information. Thank you both for helping me with this, it’s a subtle thing but I now understand better. Great tip for searching in VS Code!

cheers!

I’m so glad you found this helpful. Also, if you are finding regexp a bit confusing, well they are! But try to understand the fundamentals of them. I finally got them a little a bit with FCC lessons on Regexp!

They are not always necessary, but it is a nice extra tool to have.

Happy learning!