c# - 在 MS Word 中使用正则表达式替换文本 - C#

标签 c# regex ms-word

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

相关文章:

c# - 将 async wait 与 AcquireTokenForClient().ExecuteAsync 一起使用的正确方法

c# - 我应该如何让集合的成员知道他们的 "siblings"与其位置的关系

c# - HTTP 状态 403 : Forbidden exception using certificate to authenticate ASP. NET Web 服务

php - 获取函数调用的第一个参数的字符串

vba - 在 VBA 中将字体大小减小 1 步

c# - 端口转发 (NAT UPNP) 错误

javascript - 如何将重复模式与它们之间的可选空格匹配?

regex - vim中的非贪婪多行搜索

javascript - 文档模板 : JavaScript as replacement for Word?

java - Doc4j - 使用文档中的表格将 docx 转换为 PDF 时遇到问题