意外地重复单词是编写者常犯的错误。 可以使用正则表达式标识重复的单词,如以下测试示例所示。
static void Main(string[] args)
{
string pattern = @"\\b(\\w+?)\\s\\1\\b";
string input = "This this is a nice day. What about this? This tastes good. I saw a a dog.";
foreach (Match match in Regex.Matches(input, pattern, RegexOptions.IgnoreCase))
Console.WriteLine("{0} (duplicates '{1}') at position {2}", match.Value, match.Groups[1].Value, match.Index);
}
输出:
This this (duplicates ‘This’) at position 0
a a (duplicates ‘a’) at position 66
请按任意键继续. . .
通过将正则表达式选项设置为 Regex.Matches,调用 RegexOptions.IgnoreCase 方法。
因此,匹配操作不区分大小写,此示例将子字符串“This this”标识为重复。
输入字符串包括子字符串“this? This”。 但是,由于插入标点符号,该子字符串不被标识为重复。
正则表达式模式 \\b(\\w+?)\\s\\1\\b 的解释如下:
模式 解释
\\b 在单词边界处开始。
(\\w+?) 匹配一个或多个单词字符,但字符要尽可能的少。 它们一起构成可称为 \\1 的组。
\\s 与空白字符匹配。
\\1 与等于名为 \\1 的组的子字符串匹配。
\\b 与字边界匹配。