Replace the last occurrence of a word in a string - C#

前端 未结 7 1939
星月不相逢
星月不相逢 2020-12-09 14:07

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:

7条回答
  •  感动是毒
    2020-12-09 15:12

    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);
    

提交回复
热议问题