C# Word.Interop中MatchWholeWord为true时Find.Execute查找特殊字符失败如何解决
问题原因
Word的全字匹配规则仅对纯字母、数字组成的查找内容生效,#、-、_这类符号在Word的分词逻辑中不属于单词构成字符,只要查找文本包含这类字符,MatchWholeWord参数会自动失效,这也是Word客户端里对应场景下全字匹配选项变灰的根本原因。
解决方案
方案1:手动校验匹配结果(推荐)
先关闭全字匹配执行普通查找,每次命中结果后额外校验匹配内容的前后字符是否符合全字匹配要求,不符合就跳过继续查找。该方案灵活度最高,不会出现通配符转义错误的问题。
string targetText = @"#24V"; selection.Find.ClearFormatting(); // 无需开启MatchWholeWord,该场景下参数无效 selection.Find.Execute(FindText: targetText, MatchCase: true, Wrap: WdFindWrap.wdFindStop, MatchWholeWord: false); while (selection.Find.Found) { bool isWholeWordMatch = true; // 校验匹配内容的前一个字符 if (selection.Start > 0) { char preChar = selection.Document.Range(selection.Start - 1, selection.Start).Text[0]; // 可根据业务需求自定义判断规则,比如增加_作为分隔符 if (!char.IsWhiteSpace(preChar) && !char.IsPunctuation(preChar) && preChar != '\r' && preChar != '\n' && preChar != '_') { isWholeWordMatch = false; } } // 校验匹配内容的后一个字符 if (selection.End < selection.Document.Content.End) { char nextChar = selection.Document.Range(selection.End, selection.End + 1).Text[0]; if (!char.IsWhiteSpace(nextChar) && !char.IsPunctuation(nextChar) && nextChar != '\r' && nextChar != '\n' && nextChar != '_') { isWholeWordMatch = false; } } if (isWholeWordMatch) { // 此处处理符合要求的匹配结果 break; } // 不符合要求继续查找下一个 selection.Find.Execute(); }
方案2:使用通配符查找
开启通配符匹配模式,构造带边界规则的查找表达式,注意需要先对查找文本中的通配符保留字符做转义处理:
string targetText = @"#24V"; // 转义Word通配符的特殊保留字符 string escapedText = System.Text.RegularExpressions.Regex.Replace(targetText, @"([\\\?\*\[\]\{\}\(\)\<\>\!\@\^\-])", @"\$1"); // 构造边界匹配规则,仅匹配独立的目标内容 string findPattern = $"<{escapedText}>"; selection.Find.ClearFormatting(); selection.Find.MatchWildcards = true; selection.Find.Execute(FindText: findPattern, MatchCase: true, Wrap: WdFindWrap.wdFindContinue);
内容的提问来源于stack exchange,提问作者Dgo
相关产品推荐
相关产品推荐

