在MS Word中使用正则表达式替换文本-C# [英] Replace text using regular expressions in MS Word - C#

查看:156
本文介绍了在MS Word中使用正则表达式替换文本-C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Word文档,我想打开并用测试"一词替换所有社会保险号实例.

I have a Word document that I want to open and replace all instances of a social security number with the 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

I already have the code to open the document. Here's the code that would do the replacement. However, I'm having trouble with using regular expressions at this point: _wordApp.Selection.Find.Text = ; within my code. Is using regular expressions a good approach or is there a better approach? Bear in mind, I have to match any social security number... hence: \b[0-9]{3}-[0-9]{2}-[0-9]{4}\b OR \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具有内置的通配符匹配功能.它不像正则表达式那么强大,但是看起来它可以匹配社会保险号等简单模式.

MS Word has a wildcard matching capability built in. It's not as powerful as regular expressions, but it looks like it's able to match simple patterns like social security numbers.

(通配符<和>匹配开始和结束词的边界.)

(The < and > wildcards match start and end word boundaries.)

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

这篇关于在MS Word中使用正则表达式替换文本-C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆