C# 正则表达式识别重复单词

76 篇文章 1 订阅

意外地重复单词是编写者常犯的错误。 可以使用正则表达式标识重复的单词,如以下测试示例所示。

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 与字边界匹配。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

flysh05

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值