在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); }
评论