Non-capturing group (?:...)
and capturing group (...)
do not have any effect if their content is only 1 character and for capturing group if you do not use back reference to it.
You usually use groups when you want to extend the effect of quantifiers (?
, {N}
, {N,M}
, +
, *
) to not only the preceding character but to several ones (the group).
Examples:
secon(ds)?
secon(?:ds)?
will both match
secon
and
seconds
Because ?
will affect both d
and s
, in this case it will give a different result than seconds?
.
Another use of groups is when you want to use alternatives in the group:
time in (?:seconds?|hours?|minutes?) is a good example
and
time in second is a good example
time in seconds is a good example
time in hours is a good example
time in hour is a good example
time in minute is a good example
time in minutes is a good example
where you put alternatives between second(s), hour(s) and minute(s) within the group
Last but not least backreferences:
Find the words for which the first char is the same as the last one
^(\w)\w*\1$
and input:
aba
aaabbba
test
apple
car
where the first three lines will match. demo: https://regex101.com/r/nrDCvn/1