I am trying to replace string in a text file.
I use the following code:
string text = File.ReadAllText(@"c:\File1.txt");
text = text.Replace("play","123");
File.WriteAllText(@"c:\File1.txt", text);
It not only changes the word "play" to "123" but also change the word "display" to "dis123"
How to fix this problem?
Another technique you can use in this situation is to add more recognizable tokens into the text you wish to edit.. for example:
would become
You can use following snippets of code
Also, this is case sensitive make sure this is what you want.
An alternative approach, and not regex based could be the following:
Define a few extension methods:
Usage:
Prints:
You could take the advantage of "Regular expressions" here.
\b
Matches the word boundary, This will solve your problem.Read more about Regular expressions
Try changing it to
but this way it won't replace something like
play. play, play;