简体   繁体   中英

How to replace a string in Aspose.Words (C#) only if it is not part of another string?

I want to use this line of code to replace all occurrences of "2009" to "2000", but I don't it to replace occurrences where "2009" is part of something else. For example "year 2009" should not be replaced to be "year 2000", those should stay.

doc.Range.Replace("2009", "2000", options);
// "It was year 2009, and they already have collected 2009 votes."
// I want the this to change to:
// "It was year 2009, and they already have collected 2000 votes."

Is there a way to do it using version 21.9.0.

The only solution for what I think you're describing that springs to mind is to replace "year 2009" with an arbitrary placeholder and put it back after replacing the other instances. Something like this will do what you want, while being easily customisable:

doc.Range.Replace("year 2009", "mySillyPlaceholder");
doc.Range.Replace("2009", "2000");
doc.Range.Replace("mySillyPlaceholder", "year 2009");

But, ideally you'd change a numeric variable before file generation as that's the best way to ensure that it's done in the correct context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM