yatoro
@yatoro

Как выбрать повторяющиеся слова в регулярных выражениях?

Выбрать повторяющиеся слова, которые находятся непосредственно друг под другом.
Примеры:
This sentence is pretty long and
this sentence is also a test — Да
This sentence also shouldn't
match as this has no words
below. — Нет
  • Вопрос задан
  • 311 просмотров
Пригласить эксперта
Ответы на вопрос 2
Alexeytur
@Alexeytur
Мб не использовать регулярки, а сплитить текст на массивы: сначала по символу перевода строки, что разбить на строки, затем эти строки по символу пробела, чтобы разбить на слова, затем сравнивать.
public static bool CheckWords(string text)
{
    List<string[]> lines = new List<string[]>();
    string[] arr_lines = text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries );
    foreach (string line in arr_lines)
    {
        string[] arr_words = line.Split(' ');
        lines.Add(arr_words);
    }

    for (int current_line_num = 0; current_line_num < lines.Count - 1; current_line_num++)
    {
        for (int current_word_num = 0; current_word_num < lines[current_line_num].Length; current_word_num++)
        {
            if (current_word_num < lines[current_line_num + 1].Length
                && lines[current_line_num][current_word_num] == lines[current_line_num + 1][current_word_num])
            {
                return true; // совпадение!

            }
        }
    }

    return false;
}

public static void TestTexts()
{
    string text =
        @"This sentence is pretty long and
        this sentence is also a test";
    bool res = CheckWords(text);

    string text2 =
        @"This sentence also shouldn't
        match as this has no words
        below";
    bool res2 = CheckWords(text2);
}
Ответ написан
seven5674
@seven5674
Старый я уже что бы что-то в себе менять
/(\b\w+\b)(?=\s+\1)/
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы