Complex Replace operation

I have a complex replacement requirement. My source documents contains many Names and addresses and I need to loop through them find anything which looks like a Name (the name format is consistent because all the names are in format ) and replace the complete name with some Dummy data.

The Dummy Data is basically a list of fake names I have in a simple .NET array. I have managed to loop round and open/change documents ok but I cannot see how to replace with other than finding a static string and replacing with a static string. I assume I could ‘brute force’ it somehow but there must be a better way?

Any help would be very much appreciated.

Hi @daviddavis,
Yes, there is a better way to perform text substitutions in documents, you can learn more abut this navigating to the following link https://docs.aspose.com/words/net/find-and-replace/.
Now, let focus in your current requirement. Since you don’t provide the exact format that follows the names in your document I can’t give you a 100% accurate solution, but let assume that the names in the document have the following format Lastname, Name (allowing ’ and - characters) a valid solution for this scenario will be the following:

// Load the document.
Document doc = new Document("C:\\Temp\\names.docx");
// Replace all text occurrences that follow the required patern.
doc.Range.Replace(new Regex("([A-Z]+([A-Za-z][A-Za-z\\'\\-]+))+\\,\\s+([A-Z]+([A-Za-z][A-Za-z\\'\\-]+))"), "Replacement, Name");
// Save the changes in a new file.
doc.Save("C:\\Temp\\out-names.docx");

If you need further assistance don’t hesitate to ask for it.

Best!