【问题标题】:Replace text using regular expressions in MS Word - C#在 MS Word 中使用正则表达式替换文本 - C#
【发布时间】:2009-09-30 19:40:49
【问题描述】:

我有一个 Word 文档,我想打开它并用单词“test”替换社会安全号码的所有实例。

我已经有了打开文档的代码。这是进行替换的代码。但是,此时我在使用正则表达式时遇到了问题: _wordApp.Selection.Find.Text = ; 在我的代码中。使用正则表达式是一种好方法还是有更好的方法?请记住,我必须匹配任何社会安全号码......因此: \b[0-9]{3}-[0-9]{2}-[0-9]{4}\b 或 \b [0-9]{3}[0-9]{2}[0-9]{4}\b

提前谢谢...

object replaceAll = Werd.WdReplace.wdReplaceAll;

_wordApp.Selection.Find.ClearFormatting();
_wordApp.Selection.Find.Text = ;

_wordApp.Selection.Find.Replacement.ClearFormatting();
_wordApp.Selection.Find.Replacement.Text = "test";

_wordApp.Selection.Find.Execute(ref nullobj, ref nullobj, ref nullobj, ref nullobj,
                ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj,
                ref replaceAll, ref nullobj, ref nullobj, ref nullobj, ref nullobj);

【问题讨论】:

    标签: c# regex ms-word


    【解决方案1】:

    MS Word 内置了通配符匹配功能。它没有正则表达式那么强大,但看起来它能够匹配社会安全号码等简单模式。

    ( 通配符匹配开始和结束单词的边界。)

    _wordApp.Selection.Find.ClearFormatting();
    _wordApp.Selection.Find.MatchWildcards = true;
    _wordApp.Selection.Find.Text = "<[0-9]{3}-[0-9]{2}-[0-9]{4}>"; // SSN with dashes.
    
    _wordApp.Selection.Find.Replacement.ClearFormatting();
    _wordApp.Selection.Find.Replacement.Text = "test";
    
    _wordApp.Selection.Find.ClearFormatting();
    _wordApp.Selection.Find.MatchWildcards = true;
    _wordApp.Selection.Find.Text = "<[0-9]{9}>"; // SSN without dashes.
    
    _wordApp.Selection.Find.Replacement.ClearFormatting();
    _wordApp.Selection.Find.Replacement.Text = "test";
    

    【讨论】:

    • 这个答案非常接近。我不得不在这里和那里进行一些调整,但我最终得到了一些工作代码......非常感谢克里斯......
    猜你喜欢
    • 2019-06-17
    • 1970-01-01
    • 1970-01-01
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    • 2014-03-11
    相关资源
    最近更新 更多