c#通过正则表达式检查字符串中是否有单词重复出现?

济南云服务器 2025年2月6日06:01:44C#教程c#通过正则表达式检查字符串中是否有单词重复出现?已关闭评论41阅读模式

在c#编程语言中,我们可以通过正则表达式来完成很多操作,比如,验证某个字符串中的单词是否重复出现?

关键代码:

   static void Main()
    {
        string input = "This is a test test string";
        bool hasDuplicates = ContainsDuplicateWords(input);

        Console.WriteLine(hasDuplicates ? "The string contains duplicate words." : "The string does not contain duplicate words.");
    }

    static bool ContainsDuplicateWords(string text)
    {
        // 正则表达式匹配重复出现的单词
        Regex regex = new Regex(@"\b(\w+)\b(?=.*\b\1\b)", RegexOptions.IgnoreCase);
        return regex.IsMatch(text);
    }

济南云服务器
  • 本文由 发表于 2025年2月6日06:01:44
  • 转载请务必保留本文链接:http://news.hcsw666.com/1999