I have a problem where I need to replace the last occurrence of a word in a string.
Situation: I am given a string which is in this format:
The solution can be implemented even more simple with a single line:
static string ReplaceLastOccurrence(string str, string toReplace, string replacement)
{
return Regex.Replace(str, $@"^(.*){toReplace}(.*?)$", $"$1{replacement}$2");
}
Hereby we take advantage of the greediness of the regex asterisk operator. The function is used like this:
var s = "F:/feb11/MFrame/Templates/feb11";
var tnaName = "feb11";
var r = ReplaceLastOccurrence(s,tnaName, string.Empty);