Loading ...

Regex for duplicate ones | CodeAsp.Net

Regex for duplicate ones

Posted in: ASP.NET Topics  »  Getting Started / General ASP.NET
Subscribe to RSS
  • peter-smith

    Hi Experts,

    I have the following string : AAAA BBB CCCC DD EEEE FFFFFFF now I want the output A B C D E F from this string with regex . How can I do it ? I am working in C#.

     
  •   Answered
    raghav_khunger

    #region Using Directives
    
    using System;
    using System.Text.RegularExpressions;
    
    #endregion
    
    public class Example
    {
        static void Main()
        {
            string input = "AAAA BBB CCCC DD EEEE FFFFFFF";
            string regex = @"(.)(\1)+";
            string output = Regex.Replace(input, regex, "$1");
            Console.WriteLine(output);
            Console.ReadLine();
            //Output: A B C D E F
        }
    }


    Explanation of regex:

    (.)(\1)+

    Match the regular expression below and capture its match into backreference number 1 «(.)»

       Match any single character that is not a line break character «.»

    Match the regular expression below and capture its match into backreference number 2 «(\1)+»

       Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»

       Note: You repeated the capturing group itself.  The group will capture only the last iteration.  Put a capturing group around the repeated group to capture all iterations. «+»

       Match the same text as most recently matched by capturing group number 1 «\1»

     

    Created with RegexBuddy

    <b>[<a href="https://mvp.support.microsoft.com/profile/Raghav">ASP.NET MVP</a>]  [<a href="https://www.microsoftcommunitycontributor.com">Microsoft® Community Contributor</a>] [<a href="http://www.dzone.com/aboutmvb">Dzone MVB</a>] [<a href="https://twitter.com/#!/RaghavKhunger">Follow me on Twitter</a>]</b> <br/><br/><b>[<a href="http://codeasp.net/wiki/view/10/how-to-ask-questions-on-forums">How to ask questions on forums</a>]</b> <br/><br/> "Success does not come to those who wait . . . and it does not wait for anyone to come to it." Anonymous <br/> "Success is simply a matter of luck. Ask any failure." Anonymous
     
  • Page 1 of 1 (2 items)