I have a regular expression in javascript that I don't understand what the function of the parentheses is, because when I remove them the regular expression no longer works and accepts 4 digits or more
/^(\d{4}|\d{6})$/g
I have a regular expression in javascript that I don't understand what the function of the parentheses is, because when I remove them the regular expression no longer works and accepts 4 digits or more
/^(\d{4}|\d{6})$/g
The parentheses
()
serve to group and additionally to capture (capture means to be able to retrieve later the piece that has been found inside the parentheses).Non-capturing parentheses
(?:)
are for grouping only.In your regular expression, the use of parentheses (parentheses without capturing would suffice) is necessary because removing them leaves you with the following:
As you know, it
|
is used to separate two expressions. By removing the parentheses, the beginning of the line^
is part of the expression on the left, while the end of the line$
is part of the expression on the right. So that expression means:Which allows you to put numbers of more than 6 digits or even letters as long as it ends with 6 digits or the first 4 are digits.
So what you really want is to have a start and end for each part of the expression, which is why you used parentheses to group the two options.
If you didn't want to use parentheses, an equivalent expression would have been:
That is, we add
^
and$
to both sides.Another option could have been:
That is: Start of the string, 4 numbers, and then optionally
?
two numbers. Notice that I use a group to group the two numbers together so that it?
affects both of them at the same time. In this way either the two numbers appear or neither appears.NOTE
If it is not intended to capture what is inside the parentheses, then it is considered more appropriate to use non- capturing parentheses. For example: