[英]Replace text using regular expressions in 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內置了通配符匹配功能。它沒有正則表達式那么強大,但看起來它能夠匹配社交安全號碼等簡單模式。
(<和>通配符匹配開始和結束字邊界。)
_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";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.