搜索/突出显示word文档中的特定单词

时间:2013-10-04 12:37:31

标签: c# search ms-word

我可以使用我的代码搜索/突出显示单词文档中的特定单词。但下面是我面临的问题。

如果搜索词是“it”,那么它搜索“it”并且也搜索w“it”nessed。我只想搜索“它”这个词。我该如何解决这个问题?

foreach (Word.Range w in doc.Words)
{
    for (int i = 1; i < xmlnode.Count; i++)
    {
        XmlAttributeCollection xmlattrc = xmlnode[i].Attributes;
        object text = xmlnode[i].FirstChild.InnerText;//search words are in xml file

        if (w.Text.Trim() == text.ToString())
        {
            w.Font.Bold = 1;
            w.HighlightColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkYellow;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

尝试使用String.Compare方法:http://msdn.microsoft.com/library/vstudio/e6883c06.aspx

public static int Compare(
    string strA,
    string strB,
    StringComparison comparisonType
)

[编辑]要搜索包含开头和结尾空格的单词,请尝试使用RegEx,例如:

using System.Text.RegularExpressions;

Regex myReg ex = new Regex("^\s.*\s$");
bool bFound = myRegex.IsMatch(text);