How to replace consecutive characters with only one using RegEx in C#

1 Answer

0 votes
using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string input = "aaaabbbccdddddd";

        // Matches any character (.) followed by itself one or more times (\1+)
        string pattern = @"(.)\1+";

        // Replaces with the first captured group
        string result = Regex.Replace(input, pattern, "$1");

        Console.WriteLine("Original: " + input);
        Console.WriteLine("Modified: " + result);
    }
}



/*
run:

Original: aaaabbbccdddddd
Modified: abcd

*/

 



answered Jun 6, 2025 by avibootz
...