使用正则表达式 (\b\w+\b)\s+\1 可以查找相邻重复的单词。该模式通过捕获组记录第一个单词,并利用反向引用 \1 匹配紧随其后的相同内容,中间用 \s+ 处理空格差异。

(\b\w+\b)\s+\1 如何匹配连续文本中的重复项?
这个正则表达式能准确识别出文本中紧挨着的重复单词。它利用 \b 界定单词边界,确保只匹配完整的词,并通过 \s+ 兼容单个或多个空格的情况。

using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string text = "This is is a test test sentence.";
string pattern = @"(\b\w+\b)\s+\1";
MatchCollection matches = Regex.Matches(text, pattern);
foreach (Match match in matches)
{
Console.WriteLine($"Found: {match.Value}");
}
}
}
如何处理大小写不敏感的重复单词查找?
默认情况下正则区分大小写,若需忽略大小写差异(如 Hello hello),应添加 RegexOptions.IgnoreCase 标志。这能扩大匹配范围,适应更自然的文本场景。

using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string text = "Hello hello world World.";
string pattern = @"(\b\w+\b)\s+\1";
// 使用 IgnoreCase 选项
MatchCollection matches = Regex.Matches(text, pattern, RegexOptions.IgnoreCase);
foreach (Match match in matches)
{
Console.WriteLine($"Found: {match.Value}");
}
}
}
如果重复单词之间包含换行符会怎样?
默认的 \s+ 可以匹配换行符,因此即使重复单词被换行分隔,也能被正确捕获。但在某些严格模式下,可能需要显式指定 [\s\r\n]+ 以确保兼容性。


















