4

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?

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
user3748973
  • 449
  • 2
  • 8
  • 24
  • 1
    Your pattern does not match anything. Fix regex. – Karolis Kajenas May 19 '17 at 04:52
  • Why not use the regex option right to left and find first occurrence. You could use string method LastIndexOf("abc") instead of Regex which I would recommend. – jdweng May 19 '17 at 04:52
  • Check out this [link](https://stackoverflow.com/questions/14825949/replace-the-last-occurrence-of-a-word-in-a-string-c-sharp/67792482#67792482) for a small method that could do that. – Mimina Jun 01 '21 at 16:18

4 Answers4

3

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));       
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
2

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

Drew Aguirre
  • 375
  • 2
  • 15
0

C# -Replace First and Last occurrence of certain string

Example:

string mystring = "123xyz123asd123rea";

In the above string the value 123 was repeated thrice, now we will see how to replace the first and last occurrence of value "123" with custom value.

public static string ReplaceFirstOccurence(string originalValue, string occurenceValue, string newValue)
    {
        if (string.IsNullOrEmpty(originalValue))
            return string.Empty;
        if (string.IsNullOrEmpty(occurenceValue))
            return originalValue;
        if (string.IsNullOrEmpty(newValue))
            return originalValue;
        int startindex = originalValue.IndexOf(occurenceValue);
        return originalValue.Remove(startindex, occurenceValue.Length).Insert(startindex, newValue);
    }


    public static string ReplaceLastOccurence(string originalValue, string occurenceValue, string newValue)
    {
        if (string.IsNullOrEmpty(originalValue))
            return string.Empty;
        if (string.IsNullOrEmpty(occurenceValue))
            return originalValue;
        if (string.IsNullOrEmpty(newValue))
            return originalValue;
        int startindex = originalValue.LastIndexOf(occurenceValue);
        return originalValue.Remove(startindex, occurenceValue.Length).Insert(startindex, newValue);
    }

In the above example, we just finding the start index of the value, removing those value and inserting the new value.

Hope it helps......

Ketan
  • 79
  • 1
  • 9
0

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.

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122