Loading ...

Regex for duplicate ones

Who is online?  0 guests and 0 members
home  »  forums   »  asp.net topics   »  getting started / general asp.net   » Regex for duplicate ones

Regex for duplicate ones

Posts under the topic: Regex for duplicate ones

Posted: 10/19/2010

Lurker 100  points  Lurker
  • Joined on: 9/11/2010
  • Posts: 20

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#.


tags regex

Posted: 10/19/2010

Guru 16813  points  Guru
  • Joined on: 4/19/2009
  • Posts: 490
  Answered

#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


tags REGEX, C#
Page 1 of 1 (2 items)