Using non-capturing groups is useful for handling repeating patterns that you don't necessarily want to keep individually.
For example, lets say you're parsing out people's full names. A person can have any number of first and middle names, but only one last name. You want to capture their full name as well as their last name.
You know you can match the name segments with repeated \w+\s+
but because you don't know how many first/middle names the person has, this presents a problem.
You consider something like ^(\w+\s+)*(\w+)$
. This will capture the last name... but what capture group is it in? There's no way to know without already knowing how many first/middle names the person has.
That's where non-capturing groups come in. You need to repeat the \w+\s+
pattern, but you don't necessarily care about the specific values it grabs.
Now your expression looks like ^(?:\w+\s+)*(\w+)$
.
The full result is the person's whole name and capture group one is their last name. No more guessing where results are stored!
In your case, a look-ahead should suffice, but that doesn't mean non-capturing groups don't have their uses.