Search⌘ K
AI Features

Using Regular Expressions in C# with Groups

Explore how to create and use groups in C# regular expressions to capture specific parts of matched strings. Understand how to access groups by index or name, use nested groups, and retrieve details like group value, position, and success status.

Groups

Groups are a way of subdividing the match that regular expressions find. We specify groups with parentheses in regular expressions.

For example, we have the following input string:

The quick brown fox jumps over the lazy dog.

To match all the words in this string, we use the following regular expression:

C#
using System.Text.RegularExpressions;
class HelloWorld
{
static void Main()
{
string text = "The quick brown fox jumped over the lazy dog.";
Match match = Regex.Match(text, "\\w+");
System.Console.WriteLine(match.Groups[0]);
}
}

The regular expression \w+ matches the first word The. However, what if we want to match only the first three words? We can use a group for this:

(\w+) (\w+) (\w+)

This regular expression matches “The quick brown.”

Accessing group

...