How are non-capturing groups, i.e., (?:), used in regular expressions and what are they good for?
How are non-capturing groups, i.e., (?:) , used in regular expressions and what are
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Let me try to explain this with an example.
Consider the following text:
Now, if I apply the regex below over it (I did not escape the slashes for clarity; when using it, slashes would have to be escaped to
\/)…… I would get the following result:
But I don’t care about the protocol — I just want the host and path of the URL. So, I change the regex to include the non-capturing group
(?:).Now, my result looks like this:
See? The first group has not been captured. The parser uses it to match the text, but ignores it later, in the final result.
EDIT:
As requested, let me try to explain groups too.
Well, groups serve many purposes. They can help you to extract exact information from a bigger match (which can also be named), they let you rematch a previous matched group, and can be used for substitutions. Let’s try some examples, shall we?
Imagine you have some kind of XML or HTML (be aware that regex may not be the best tool for the job, but it is nice as an example). You want to parse the tags, so you could do something like this (I have added spaces to make it easier to understand):
The first regex has a named group (TAG), while the second one uses a common group. Both regexes do the same thing: they use the value from the first group (the name of the tag) to match the closing tag. The difference is that the first one uses the name to match the value, and the second one uses the group index (which starts at 1).
Let’s try some substitutions now. Consider the following text:
Now, let’s use this dumb regex over it:
This regex matches words with at least 3 characters, and uses groups to separate the first three letters. The result is this:
So, if we apply the substitution string:
… over it, we are trying to use the first group, add an underscore, use the third group, then the second group, add another underscore, and then the fourth group. The resulting string would be like the one below.
You can use named groups for substitutions too, using
${name}.To play around with regexes, I recommend http://regex101.com/, which offers a good amount of details on how the regex works; it also offers a few regex engines to choose from.