Search code examples
c#ms-wordspire.doc

Find and replace all the words starting with a specific character


I have a requirement to replace all words starting with $ in a Word document

sample:

$Address
$Lastname etc.

Now at the beginning I must create a list with all words that start with $ After that I replace all words

$Lastname -> Waning etc

How can I create a list with all words starting with $ in spiredoc ?


Solution

  • You can use a regular expression and FillAllPattern() method to find the words that start with $ and return results in TextSelection collection.

    Regex regex = new Regex(@"\$\w+\b");
    TextSelection[] selections = document.FindAllPattern(regex);
    

    To replace string that matches a specific regex with a new string, use Document.Replace(System.Text.RegularExpressions.Regex Pattern, string replace) method.