Reputation: 23
im trying to understand this regular expression written for visa cards but i have a problem with understanding the grouping and non capturing group.
All Visa card numbers start with a 4. New cards have 16 digits. Old cards have 13.
^4[0-9]{12}(?:[0-9]{3})?$
i understand this part:
^4[0-9]{12}
and the question mark at the end (because the last 3 digits are optional) but i dont understand why we need to group the last part and also if we do it why do we need to include
?:
i mean if there are 3 more digits we need to capture them, so why are we using a non capturing group ?
Upvotes: 1
Views: 306
Reputation: 1377
The last part, (?:[0-9]{3})?
, is grouped with (?: )
so that the final ?
will apply to the whole group. If the grouping is left out, the regular expression becomes [0-9]{3}?
, which actually means something entirely different. {x,y}?
means to match the previous expression anywhere from x to y times, but preferring to match as few times as possible (i.e. it is non-greedy). {x}?
doesn't make any sense to use, as it means to match exactly x times, preferring as few as possible—it is identical to {x}
.
The reason the non-capturing grouping, (?: )
, is used, is because we don't need to capture the last three digits. There's a difference between matching a pattern, which is what you're doing when verifying a credit card number, and capturing a portion of it with parentheses. Matching just tells you whether the input matches the regular expression, which is all we care about here. Capturing allows you to get the value of a portion of the input string. You could use regular capturing parentheses here, and it would still match just the same, but it would needlessly capture the last three digits, probably being (slightly) slower and using (slightly) more memory.
Upvotes: 3
Reputation: 174696
why we need to group the last part?
So that we could make the last three as optional else the last character alone would be made optional. (\d\d)?
not equal to \d\d?
.
(?:...)
called non-capturing group usually used to group characters or patterns, You may use capturing group (...)
also, only if you want to capture the last three digits in a 16 digits card no.
Upvotes: 2