views:

26

answers:

1

Hello,

I have a C# program where I am using a lot of RegEx.Replace to replace text in my text file.

Here is my problem.

In my text file, I have a code such as "M6T1". This code is listed in numerous places in the text file.

However, I only want to delete it from the bottom (last instance) in the text file. There will always be a "M6T1" at the bottom of the text file, but it is not always the last line. It could be the 3rd line from the bottom, the 5th line from the bottom etc.

I only want to get rid of the last instance of "M6T1" so RegEx.Replace won't work here. I don't want to interfer with the other "M6T1"'s in the other locations in the text file.

Can someone please give me a solution to this problem?

Thanks

+5  A: 
var needle = "M6T1";
var ix = str.LastIndexOf(needle);
str = str.Substring(0, ix) + str.Substring(ix + needle.Length);
kevingessner
+1 for `needle` (though I suppose to be *perfect* `str` should have been `haystack` :)
egrunin
@egrunin - Using `needle` and `haystack` is one of the few things PHP does right.
kevingessner