I'm trying to get my head around this concept, but I really can't see how it's useful, so I'm assuming I'm missing the point.
For example -
This regex /([0-9]+)(?:st|nd|rd|th)?/ will match numbers with or without a 'st', 'rd' etc. suffix.
So "1st".match(/([0-9]+)(?:st|nd|rd|th)?/g) returns ["1st"]
"1".match(/([0-9]+)(?:st|nd|rd|th)?/g) returns ["1"]
However, this still works exactly the same without the (?:) par!
"1st".match(/([0-9]+)(st|nd|rd|th)?/g) returns ["1st"]
Thanks...
Non-capture grouping is faster because the regex engine doesn't have to keep track of the match. It can be a good idea not to capture what you don't need to capture for the sake of clarity. For example:
(foo|bar)((z|q)s?)?
This is somewhat contrived, but you could easily apply it to a real regex. You can match fooz or foozs. We are interested in the foo and bar part as well as z or q, but we don't care about the optional s. So which part is z or q? Is it capture group 2 or 3? Imagine if we had (?:(z|q) instead. Now, we know there are only two capture groups so we don't have to make this mental jump.
Sometimes non-capturing is necessary such as for JavaScript's .split.
If separator contains capturing parentheses, matched results are returned in the array.
If you want to use grouping for splits but you don't want to include the split regex in the array, you must use non-capturing groups.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With