How to get rid of duplicates in regular expression

Suppose I had the line, "cats cats cats and dogs dogs dogs."

What regular expression would I use to replace this line with the words "cats and dogs." those. duplicate removal. However, the expression should only remove duplicates that follow each other. For instance:

"cats cats cats and dogs dogs dogs and cats cats and dogs dogs"

Will return:

"cats and dogs and cats and dogs"

+5
source share
4 answers

Replace (\w+)\s+\1with$1

, . global , cats cats cats cats

\1 regex .

Try:

str = "cats cats cats and dogs dogs dogs and cats cats and dogs dogs";
str = Regex.Replace(str, @"(\b\w+\b)\s+(\1(\s+|$))+", "$1 ");
Console.WriteLine(str);
+2
resultString = Regex.Replace(subjectString, @"\b(\w+)(?:\s+\1\b)+", "$1");

.

:

\b                 # assert that we are at a word boundary
                   # (we only want to match whole words)
(\w+)              # match one word, capture into backreference #1
(?:                # start of non-capturing, repeating group
   \s+             # match at least one space
   \1              # match the same word as previously captured
   \b              # as long as we match it completely
)+                 # do this at least once
+9

There is no doubt that a smaller regex exists, but it looks like this does the trick:

string somestring = "cats cats cats and dogs dogs dogs and cats cats and dogs dogs";
Regex regex = new Regex(@"(\w+)\s(?:\1\s)*(?:\1(\s|$))");
string result = regex.Replace(somestring, "$1$2");

It also takes into account the last “dogs” that do not end with a space.

+1
source

Try using the following code.



using System;
using System.Text.RegularExpressions;

namespace ConsoleApplication1 { /// <summary> ///
/// A description of the regular expression: ///
/// Match expression but don't capture it. [^|\s+] /// Select from 2 alternatives /// Beginning of line or string /// Whitespace, one or more repetitions /// [1]: A numbered capture group. [(\w+)(?:\s+|$)] /// (\w+)(?:\s+|$) /// [2]: A numbered capture group. [\w+] /// Alphanumeric, one or more repetitions /// Match expression but don't capture it. [\s+|$] /// Select from 2 alternatives /// Whitespace, one or more repetitions /// End of line or string /// [3]: A numbered capture group. [\1|\2], one or more repetitions /// Select from 2 alternatives /// Backreference to capture number: 1 /// Backreference to capture number: 2 ///
/// /// </summary> class Class1 { /// /// Point d'entrée principal de l'application. /// static void Main(string[] args) { Regex regex = new Regex( "(?:^|\s+)((\w+)(?:\s+|$))(\1|\2)+", RegexOptions.IgnoreCase | RegexOptions.Compiled ); string str = "cats cats cats and dogs dogs dogs and cats cats and dogs dogs"; string regexReplace = " $1";

Console.WriteLine("Before :" + str); str = regex.Replace(str,regexReplace); Console.WriteLine("After :" + str); } }

}

0
source

All Articles