Find and replace all the words starting with a specific character

2.6k Views Asked by At

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 ?

2

There are 2 best solutions below

1
On BEST ANSWER

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.

1
On

Read the file. Split the words with Split() and keep result in list

string s = "word file text";
List<string> words = s.Split(' ');

and control items in List

List<string> result = new List<string>();
foreach(string item in words)
{
    if (item .StartsWith("$")) 
    {
        result.Add(item);
    }
}

result returns strings which contain $