1. Technology
Send to a Friend via Email

Regular Expressions

16. Non-Capturing Groups

clr gif

In the last two tutorials we have looked at two different uses for groups.

  1. to allow us to test for multiple repetitions of a group of characters
  2. to allow us to use a backreference to refer to the actual text that was matched

In complex regular expressions you may have the situation arise where you wish to use a large number of groups some of which are there for repetition matching and some of which are there to provide back references. By default the text matching each group is loaded into the backreference array. Where we have lots of groups and only need to be able to reference some of them from the backreference array we can override this default behaviour to tell the regular expression that certain groups are there only for repetition handling and do not need to be captured and stored in the backreference array.

We specify that a particular group is not to be captured in the backreference array by placing ?: immediately after the opening parenthesis. So if we wish to search for any number of occurrences of "an" followed by a single "b" and then access the entire string from the backreference array without having the individual occurrences of "an" loaded to the backreference array then we can use the following combination of groups where only the string that matches the outer group is captured because we have defined the inner group as non-capturing.

var re = /((?:an)+b)/;

©2014 About.com. All rights reserved.