Replace text using regular expressions in MS Word - C #

I have a Word document that I want to open and replace all instances of a social security number with the word "test".

I already have a code to open the document. Here is the code that will replace. However, I am having problems using regular expressions at the moment: _wordApp.Selection.Find.Text =; in my code. Is regular expression a good approach or is there a better approach? Keep in mind that I must match any social security number ... therefore: \ b [0-9] {3} - [0-9] {2} - [0-9] {4} \ b OR \ b [0-9] {3} [0-9] {2} [0-9] {4} \ b

Thanks in advance...

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); 
+4
source share
1 answer

MS Word has a built-in character matching feature. It is not as powerful as regular expressions, but it seems that it is able to match simple patterns such as social security numbers.

(The characters <and> correspond to the boundaries of the beginning and end of the 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"; 
+4
source

All Articles