An alternative approach, and not regex based could be the following:
Define a few extension methods:
static class Exts
{
public static string GetLettersAndDigits(this string source)
{
return source.Where(char.IsLetterOrDigit)
.Aggregate(new StringBuilder(), (acc, x) => acc.Append(x))
.ToString();
}
public static string ReplaceWord(this string source, string word, string newWord)
{
return String.Join(" ", source
.Split(new string[] { " " }, StringSplitOptions.None)
.Select(x =>
{
var w = x.GetLettersAndDigits();
return w == word ? x.Replace(w, newWord) : x;
}));
}
}
Usage:
var input = File.ReadAllText(@"C:\test.txt");
var output = input.ReplaceWord("play", "123");
Console.WriteLine(input);
Console.WriteLine(output);
Prints:
This is a test: display play, play display -play !play - maybe it's working?
This is a test: display 123, 123 display -123 !123 - maybe it's working?