C# Word.Interop Find.Execute MatchWholeWord: true 失败

C# Word.Interop Find.Execute MatchWholeWord: true fails

我使用 Find.Excecute() 在文档中查找整个单词。但如果 FindText 包含“#”、“-”或“”,Find.Excecute() 将失败。它会查找所有以 FindText 开头或包括在内的单词。 此外,在单词搜索时,如果搜索名称包含上述字符之一,则“搜索整个单词”将变为非活动状态。 Find.Execute() 如何找到包含“#”、“-”或“”的整个单词?

尽管 MatchWholeWord 设置为 true

,此代码也能找到“#24V_ABCD”
string name = @"#24V";
selection.Find.Execute(FindText: name, MatchCase: true, Wrap: WdFindWrap.wdFindContinue, MatchWholeWord: true);

'?'和'-'用于单词搜索中的搜索通配符,这将导致您的搜索失败。

我不确定“#”。

字数以一种特殊的方式计算字数。 #24V_1A其实就是4个字:'#' '24V' '_' '1A'。 因此,搜索整个单词失败。

一个解决方案是增加 Find.Execute() 找到的范围,直到到达单词的末尾。然后可以将真实单词与搜索字符串进行比较。必须调用 Find.Execute() 直到到达文档末尾或找到搜索字符串。以下代码片段忽略了#24V_1A,但找到了#24V.

string name = "#24V";
selection.Find.Execute(FindText: name, MatchCase: true, Wrap: WdFindWrap.wdFindContinue, MatchWholeWord: true);

// arbitrary value of 32 words in a word will be fine for me
string[] delimiterChars = { "\r", " ", ",", ";", ".", ":", "\t", "!", "?", "\a", "\v" };
for (int j = 0; j < 32; j++)
{
    string foundName = "";
    selection.MoveRight(WdUnits.wdWord, 1, WdMovementType.wdExtend);
    string text = selection.Range.Text; // debug value
    string lastChar = text.Substring(text.Length - 1);
    if (delimiterChars.Contains(lastChar))
    {
        // found end of word
        foundName = text.Substring(0, text.Length - 1);

        if (foundName == name)
        {
            break;
        }
    }
}