使用MS Word中的正则表达式替换文本 – C#

我有一个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); 

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

(<和>通配符匹配开始和结束字边界。)

 _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";