[Solved] Regexp – Delete the one word before XXX, remove XXX too [closed]


Do a single regex replacement:

string input = @"Hello World XXX Goodbye XXX Rabbit!";
Regex rgx = new Regex(@"\s*\w+\s+(?:XXX|xxx)");  // or maybe [Xx]{3}
string result = rgx.Replace(input, "", 1);
Console.WriteLine(result);

Hello Goodbye XXX Rabbit!

Demo

This replacement only would target XXX for removal if it be preceded by a word (one character or more). Explore the demo to see how it would behave with various inputs.

We can also make the search pattern case insensitive via this:

Regex rgx = new Regex(@"\s*\w+\s+XXX", RegexOptions.IgnoreCase);
                                       ^^^^^ add this

15

solved Regexp – Delete the one word before XXX, remove XXX too [closed]