Vinicius Quinafelex Alves

🌐Ler em português

[C#] Regex named group

Regex is a pattern that describes a certain amount of text, and can be used to locate substrings matching a pattern within a text. For example, it can be used to locate numbers, email addresses, links, or any other pattern of characters.

Regex enables the use of groups to capture specific parts of data within a pattern.

The C# example below demonstrates how to extract all emails from an input text. Note that the regex pattern for email is simplified for legibility, and should not be used in production.

Without named group

public static IEnumerable<Mail> ExtractMail(string input)
{
    var pattern = @"([a-z]+)@([a-z]+(.[a-z]+)*)";
    var regex = new Regex(pattern, RegexOptions.Compiled);

    foreach (Match match in regex.Matches(input))
    {
        yield return new Mail(
            username: match.Groups[1].Value,
            domain: match.Groups[2].Value);
    }
}

With named group

public static IEnumerable<Mail> ExtractMail(string input)
{
    var pattern = @"(?<username>[a-z]+)@(?<domain>[a-z]+(.[a-z]+)*)";
    var regex = new Regex(pattern, RegexOptions.Compiled);

    foreach (Match match in regex.Matches(input))
    {
        yield return new Mail(
            username: match.Groups["username"].Value,
            domain: match.Groups["domain"].Value);
    }
}