2013-11-22 47 views
0

我正在尝试编写一个应用程序来搜索word文档中的所有匹配项,其中some_text是<和>之间的任何字符串。当我找到每场比赛时,我想要在每场比赛中存储/显示/做些事情。如何从word文档中获得匹配通配符的所有字符串

这是我到目前为止有:

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 
} 
+0

你不能使用正则表达式吗?你没有访问Word文档的纯文本吗? – kaptan

+0

你的答复在某处是否有答案?你基本上问我刚才在我的问题中提出的问题。我不知道如何访问Word文档的纯文本。 – worktech

+0

不,没有回答伪装:>我只是认为它是更有效和更容易使用正则表达式。但是,如果你不能访问纯文本,那么这是一个不同的故事。 – kaptan

回答

1

事实证明,范围是每一个找到的字符串重新定义。您可以访问每一个找到的文字为:

rng.Text 

,你可以得到更大的范围内找到的文本字符的位置:

rng.Start 
rng.End 

所以我能够通过声明仅包含本地范围做到这一点查找循环中找到的字符串。我用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(); 
    } 
相关问题