Replace last specific string

Viewed 2215

I have a string like this :

string myText = "abc def ghi 123 abc def ghi 123 abc def";

I want to replace only last abc with empty.

Here is my code:

string pattern2 = "([abc])$";
string replacement2 = "";
Regex regEx = new Regex(pattern2);
var b = Regex.Replace(regEx.Replace(myText, replacement2), @"\s", " ");

It does not work properly, so how can it be done?

4 Answers

I want to replace only last abc with empty.

You almost had it, but regex works from left to right. If you instead have the parser work, right to left, and to handle any proceeding text, it can be done in regex.

string myText  = "abc def ghi 123 abc def ghi 123 abc def";
string pattern = "(abc)(.*?)$";

Regex.Replace(myText, pattern, "$2", RegexOptions.RightToLeft);

Regex replace returns the string abc def ghi 123 abc def ghi 123 def.

Note there are two spaces in the result...you asked to replace the abc with "empty"; and that is what it did. One can account for the space issue as needed.

Related