C#字符串匹配关键词列表失效:如何修复if语句的匹配识别问题?
解决C# ColorizeText函数关键词匹配失效问题
问题根源
你的代码无法匹配关键词的核心原因有两个:
- 仅用
Split(' ')拆分文本,只能处理单个空格,无法应对多空格、制表符、换行等空白字符,还会保留单词前后的标点(比如"Block,"、"Weak."),导致拆分后的word和关键词列表里的纯字符串不匹配。 - 默认的
Contains是大小写敏感的,如果输入文本中的单词大小写和关键词不一致(比如输入"block"而关键词是"Block"),也会匹配失败。
修复方案
方案1:清理单词+大小写不敏感匹配
先清理拆分后单词的标点,再用大小写不敏感的集合来做匹配,同时处理多种空白字符:
public static string ColorizeText(string text) { List<string> keywords = new() { "Block", "Vulnerable", "Weak" }; // 用大小写不敏感的哈希集合,提升匹配效率 HashSet<string> keywordSet = new HashSet<string>(keywords, StringComparer.OrdinalIgnoreCase); string colorizedText = string.Empty; // 按任意空白字符拆分,同时移除空条目 foreach (string rawWord in text.Split(new[] {' ', '\t', '\n', '\r'}, StringSplitOptions.RemoveEmptyEntries)) { // 移除单词首尾的非字母数字字符 string cleanedWord = System.Text.RegularExpressions.Regex.Replace(rawWord, @"^[^\w]+|[^\w]+$", ""); if (keywordSet.Contains(cleanedWord)) { // 保留原始单词的格式(比如标点),只替换核心关键词部分 colorizedText += rawWord.Replace(cleanedWord, $"<color=yellow>{cleanedWord}</color>") + " "; } else { colorizedText += rawWord + " "; } } // 移除末尾多余的空格 return colorizedText.TrimEnd(); }
方案2:正则表达式直接替换(更简洁)
用正则匹配完整单词,支持大小写不敏感,一步完成替换:
public static string ColorizeText(string text) { List<string> keywords = new() { "Block", "Vulnerable", "Weak" }; // 构建正则模式:匹配任意关键词作为完整单词,转义特殊字符以防出错 string pattern = @"\b(" + string.Join("|", keywords.Select(System.Text.RegularExpressions.Regex.Escape)) + @")\b"; // 替换匹配到的单词,忽略大小写 return System.Text.RegularExpressions.Regex.Replace(text, pattern, @"<color=yellow>$&</color>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); }
为什么之前的代码失效?
举个例子:如果输入是"This Block is Weak!",用Split(' ')拆分后会得到"Block"(正常)和"Weak!"(带感叹号),此时keywords.Contains("Weak!")必然返回false。而你硬编码匹配时用了带标点的字符串,所以能成功,但模块化匹配用的是纯关键词,自然失效。
内容的提问来源于stack exchange,提问作者Justin Martin
相关产品推荐
相关产品推荐

