【问题标题】:How to get all strings matching wildcards from word document如何从word文档中获取所有匹配通配符的字符串
【发布时间】:2013-11-22 22:16:04
【问题描述】:

我正在尝试编写一个应用程序来搜索 word 文档中所有出现的 ,其中 some_text 是 之间的任何字符串。当我找到每场比赛时,我想对每场比赛进行存储/显示/做一些事情。

这是我目前所拥有的:

Word._Application word = new Word.Application();
Word.Documents d = word.Documents;
Word._Document doc;

doc = d.Open(strFileName);
doc.Activate();

foreach (Word.Range myStoryRange in doc.StoryRanges)
{
    myStoryRange.Find.MatchWildcards = true;
    myStoryRange.Find.Text = "[<]*[>]";
    myStoryRange.Find.Execute();

    // Somehow get the result string that matched the wildcard
}

【问题讨论】:

  • 你不能使用正则表达式吗?您无法访问 Word 文档的纯文本吗?
  • 您的回复中是否有隐藏的答案?你基本上是在问我刚刚在我的问题中提出的问题。我不知道如何访问Word文档的纯文本。
  • 不,没有伪装的答案:> 我只是认为使用正则表达式更有效,更容易。但如果您无法访问纯文本,那就另当别论了。

标签: c# .net ms-word find office-interop


【解决方案1】:

事实证明,为每个找到的字符串重新定义了 Range。您可以通过以下方式访问每个找到的文本:

rng.Text

并且可以得到更大范围内找到的文字字符位置:

rng.Start
rng.End

因此,我可以通过声明一个仅包含 Find 循环中找到的字符串的本地 Range 来做到这一点。我用 DocProperty 替换了每个文本,但你可以用它做任何你喜欢的事情:

    Word.Range rng = this.Content;
    rng.Find.MatchWildcards = true;
    rng.Find.Text = "[<]*[>]";

    while (rng.Find.Execute())
    {
        // create a local Range containing only a single found string
        object cstart = rng.Start;
        object cend   = rng.End;
        Word.Range localrng = this.Range(ref cstart, ref cend);

        // replace the text with a custom DocProperty
        Word.Field newfld = localrng.Fields.Add(localrng, Word.WdFieldType.wdFieldDocProperty, "MyDocProp", false);
        localrng.Fields.Update();
    }

【讨论】:

    猜你喜欢
    • 2015-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-06
    相关资源
    最近更新 更多