September 1, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

.NET Regular Expressions and Captures

  • March 30, 2005
  • By Tom Archer
  • Send Email »
  • More Articles »

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:

(?<time>(?:\d|\:)+)

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 email addresses of almost any format from a body of text.

About the Author

Tom Archer owns his own training company, Archer Consulting Group, which specializes in educating and mentoring .NET programmers and providing project management consulting. If you would like to find out how the Archer Consulting Group can help you reduce development costs, get your software to market faster, and increase product revenue, contact Tom through his Web site.





Page 2 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel