Предположим, что у меня была строка, "кошки кошек кошек и собаки собак собак".
Что регулярное выражение было бы я использовать для замены той строки, "кошки и собаки". т.е. удаление дубликатов. Выражение однако должно только удалить дубликаты, которые следуют друг после друга. Например:
"кошки кошек кошек и собаки собак собак и кошки кошек и собаки собак"
Возвратился бы:
"кошки и собаки и кошки и собаки"
Замените (\ w +) \ s + \ 1
на $ 1
. Делайте это в цикле, пока больше совпадений не будет найдено. Установка флага global
недостаточна, так как он не заменит третьих cats
в cats cats cats
\ 1
в регулярном выражении относится к содержимому первая захваченная группа.
Попробуйте:
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);
Несомненно, существует регулярное выражение меньшего размера, но это, кажется, помогает:
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");
Он также учитывает последние «собаки», не заканчивающиеся пробелом.
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
Попробуйте ввести следующий код.
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);
}
}
}