我有一个 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 内置了通配符匹配功能。它不如正则表达式强大,但看起来可以匹配社会安全号码等简单模式。
(< 和 > 通配符匹配开始和结束单词边界。)
_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";
关于c# - 在 MS Word 中使用正则表达式替换文本 - C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1500253/