【问题标题】:Search/Highlight a particular word in word document在 Word 文档中搜索/突出显示特定单词
【发布时间】:2013-10-04 12:37:30
【问题描述】:

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

如果搜索词是“it”,那么它会搜索“it”,也会搜索“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;
        }
    }
}

【问题讨论】:

    标签: c# search ms-word


    【解决方案1】:

    尝试使用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);
    

    【讨论】:

    • 它对我有帮助。我需要寻找带有开头和结尾空格的单词。我认为这将解决我的问题。有没有办法同样搜索?
    • 当然可以使用正则表达式:msdn.microsoft.com/en-us/library/vstudio/ms228595.aspx
    • @Robin:我在回答中添加了一个正则表达式的例子,请看一下
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多