.NET Regular Expressions and Captures

The result of a regular expression is a collection (MatchCollection) of Match objects (see Figure 1). Within each Match object is a collection (GroupCollection) of Group objects. Each Group object within the GroupCollection represents either the entire match or a sub-match that was defined via parenthesis.

Figure 1: .NET Regular Expression Class Hierarchy

Although you probably won't encounter too many situations where you work directly with captures (Capture and CaptureCollection), to present a complete picture of regular expressions, this article covers what they are and when they do come into play.

Working with Captures

One reason that you'll rarely deal with captures is that there's usually only one capture per group. Therefore, you'll generally extract your sub-match information from the Group object. This is also why you'll generally see the terms group and capture used somewhat interchangeably. However, your regular expression will yield groups with multiple captures in a few situations, so this article focuses on that.

Take a simple expression used to extract a time-formatted value:


You have a named group called time that searches for sequences of numbers and colons. Imagine using that expression to parse the following value:

Tom Archer posted at 12:34:56 today

Looking at the expression/input pair, you can see that the parser will yield three groups (including the entire match). However, what is not so obvious is that the second group will contain eight captures. The following function proves this:

using namespace System::Text;
using namespace System::Text::RegularExpressions;


void DisplayGroups(String* input, String* pattern, bool displayCats = false)
    StringBuilder* results = new StringBuilder();

    Regex* rex = new Regex(pattern);

    // for all the matches
    for (Match* match = rex->Match(input);
         match = match->NextMatch())
      results->AppendFormat(S"Match {0} at {1}\r\n",

      // for all of THIS match's groups
      GroupCollection* groups = match->Groups;
      for (int i = 0; i < groups->Count; i++)
        results->AppendFormat(S"\tGroup: Value '{0}' at Index {1}\r\n",
        if (displayCats)
          // for all of THIS group's captures
          CaptureCollection* captures = groups->Item[i]->Captures;
          for (int j = 0; j < captures->Count; j++)
            results->AppendFormat(S"\t\tCapture: Value '{0}' at Index {1}\r\n",
  catch(Exception* pe)

Calling the function in the following manner will result in what you see in Figure 2:

DisplayGroups(S"Tom Archer posted at 12:34:56 today",

Figure 2: Example of Groups vs. Captures

So, the obvious question is: Why so many captures? The second group (the inner parenthesis in the test expression) states that a sub-match can be made on any single digit or colon:


Because the input string contains eight such instances of a number or colon, you get eight captures! Therefore, while I frequently find it more convenient to use the term group to characterize the result of a sub-match, sub-matches technically result in captures.

Having said that, because groups do typically contain a single capture, you can use the two terms interchangeably unless you have a specific reason to differentiate between them—as in the example in this article.

.NET Regular Expressions and Captures

Turning Off Captures

As previously mentioned, you will not care about captures most of the time and will extract the needed information from the group collection. Therefore, I suggest simply "turning off" the capture facility. One way to do that is to specify the RegexOptions::ExplicitCapture option when constructing the Regex object. Using the example DisplayGroups function, this would look like the following:

Regex* rex = new Regex(pattern, RegexOptions::ExplicitCapture);

Another way is to use the "non-capturing groups" syntax, which simply means to follow the opening parenthesis with the "?:" combination. Once again, using the example regular expression, this would look like the following:


Figure 3 shows the results of running the DisplayGroups function without the captures. As you can see, the only object in the CaptureCollection will be that of the entire group, which is the entire match.


Figure 3: Example of Suppressing Captures

Looking Ahead

In future tips, I'll cover how to take what you've discovered so far in this series and apply it to common tasks, such as searching for and replacing text, replacing matches with substitution patterns, and finally using a very advanced expression to parse e-mail addresses of almost any format from a body of text.

About the Author

Tom Archer - MSFT

I am a Program Manager and Content Strategist for the Microsoft MSDN Online team managing the Windows Vista and Visual C++ developer centers. Before being employed at Microsoft, I was awarded MVP status for the Visual C++ product. A 20+ year veteran of programming with various languages - C++, C, Assembler, RPG III/400, PL/I, etc. - I've also written many technical books (Inside C#, Extending MFC Applications with the .NET Framework, Visual C++.NET Bible, etc.) and 100+ online articles.


  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Today's agile organizations pose operations teams with a tremendous challenge: to deploy new releases to production immediately after development and testing is completed. To ensure that applications are deployed successfully, an automatic and transparent process is required. We refer to this process as Zero Touch Deployment™. This white paper reviews two approaches to Zero Touch Deployment--a script-based solution and a release automation platform. The article discusses how each can solve the key …

  • On-demand Event Event Date: December 18, 2014 The Internet of Things (IoT) incorporates physical devices into business processes using predictive analytics. While it relies heavily on existing Internet technologies, it differs by including physical devices, specialized protocols, physical analytics, and a unique partner network. To capture the real business value of IoT, the industry must move beyond customized projects to general patterns and platforms. Check out this webcast and join industry experts as …

Most Popular Programming Stories

More for Developers

RSS Feeds