Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace last specific string

Tags:

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?

like image 769
user3748973 Avatar asked May 19 '17 04:05

user3748973


2 Answers

It is possible with String methods like LastIndexOf and Substring take a look into the following code as well as this working example

string myText = "abc def ghi 123 abc def ghi 123 abc def";
string searchStr = "abc";
int lastIndex = myText.LastIndexOf(searchStr);
if(lastIndex>=0)
  myText = myText.Substring(0,lastIndex) + myText.Substring(lastIndex+searchStr.Length);
Console.WriteLine(myText);

Please note : If you want to replace abc with any other strings then use that in between them or just use String.Format to join them like the following:

string replaceStr = "replaced";
string outputStr = String.Format("{0} {1}{2}",
                                 myText.Substring(0,lastIndex),
                                 replaceStr,
                                 myText.Substring(lastIndex+searchStr.Length));       
like image 57
sujith karivelil Avatar answered Sep 23 '22 10:09

sujith karivelil


That's an easy one, How about using the Remove method

        string textToRemove = "abc";
        string myText = "abc def ghi 123 abc def ghi 123 abc def";
        myText = myText.Remove(myText.LastIndexOf(textToRemove), textToRemove.Length);
        Console.WriteLine(myText);

Output: abc def ghi 123 abc def ghi 123 def

if you want to remove the extra space between 123 and def just + 1 on the textToRemove.Length.

Output: abc def ghi 123 abc def ghi 123 def

like image 35
Drew Aguirre Avatar answered Sep 22 '22 10:09

Drew Aguirre