Regex Non-capturing Group

Summary: in this tutorial, you will learn about regex non-capturing groups and how to use them to avoid unnecessary overhead.

Introduction to the Regex Non-capturing group

A capturing group matches a pattern and stores a match result in matching groups. To create a capturing group, you place a pattern inside the parentheses () like this:

(P)Code language: C# (cs)

In this syntax, the regex engine matches the pattern P and stores the match result inside groups, which you can access via the Groups property of the Match object.

In some situations, you want to create a group but you don’t want to capture it match result. To do that, you use a non-capturing group with the following syntax:

(?:P)Code language: C# (cs)

When you use a non-capturing group, the regex engine matches the pattern P but doesn’t store the match result in Groups.

Non-capturing groups are useful when you want to create a group and apply quantifiers, alternations, or other operations to a group of patterns but you don’t want to capture them.

Non-capturing groups also help you to write regular expressions that avoid unnecessary capture group overhead.

Regex Non-capturing group example

The following example uses a non-capturing group to match a color code in the format "#RRGGBB" or "0xRRGGBB":

using System.Text.RegularExpressions;
using static System.Console;


var text = "My favorite color is #00FF00.";
var pattern = @"(?:#|0x)([A-Fa-f0-9]{6})";

var match = Regex.Match(text, pattern);

if (match.Success)
{

    WriteLine($"Your favorite color code is {match.Groups[1].Value}");
}Code language: C# (cs)

Output:

Your favorite color code is 00FF00Code language: C# (cs)

In the regular expression pattern (?:#|0x)([A-Fa-f0-9]{6}):

  • The non-capturing group (?:#|0x) matches either the “#” symbol or the “0x” prefix.
  • The capturing group ([A-Fa-f0-9]{6}) captures the actual color code.

Summary

  • Use non-capturing groups to group patterns together without capturing the matched substrings.
Was this tutorial helpful ?