Search code examples
c#.netms-wordoffice-interop

Regarding find.replace using interop.word in C#


I have this code that superscript every number in between two x'es

doc.Find.Replacement.Font.Superscript = 1;
doc.Find.Text = "x([0-9]{1,5})x";
doc.Find.Replacement.Text = @"\1";
doc.Find.MatchWildcards = true;

doc.Find.Execute(Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Word.WdReplace.wdReplaceAll, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

I would like to have a similar function that superscript all characters between two x'es and thought that maybe this would do the trick:

doc.Find.Replacement.Font.Superscript = 1;
doc.Find.Text = "x([a-z]{1,5})x";   <-------- characters instead of numbers
doc.Find.Replacement.Text = @"\1";
doc.Find.MatchWildcards = true;

...

But it doesn't work. Also i'm not sure what the following line does.

doc.Find.Replacement.Text = @"\1";

Solution

  • Try

    doc.Find.Text = "x([a-wy-z]{1,5})x";   <-------- characters instead of numbers
    

    Because you want the "x" to "end" the matching, so it can't be part of the matching :-)

    doc.Find.Replacement.Text = @"\1";
    

    Means that it has to replace the text between the (...) with the text between the (...) (so only the x-es are removed). Clearly the formatting is done on the replaced text. \1 means the text that matched the first (...). If you had multiple (...)(...) then they would be numbered \1, \2, ...