5

I am trying to replace a single (last or next-to-last) match in a string. I have my Regular Expression already and it works, but it replaces ALL items, then I have to run back through and replace a single item.

Regex.Replace(BaseString, MatchString, ReplacementString)

I want to use MatchEvaluator but can't figure out how.

Any help?

jeffreypriebe
  • 2,267
  • 25
  • 30

3 Answers3

13

MatchEvaluator is simply a delegate. You pass in your function.

In your case, use something like:

Regex.Replace(BaseString, MatchString, delegate(Match match)
                    {
                        bool last = match.NextMatch().Index == 0;

                        if (last)
                            return match.Value;
                        else
                            return ReplacementString;
                    }, RegexOptions.Compiled);

This code skips the last match. You could also check for next-to-last match in a similar manner.

Also see this question for more information on how to use MatchEvaluator: How does MatchEvaluator in Regex.Replace work?

Community
  • 1
  • 1
jeffreypriebe
  • 2,267
  • 25
  • 30
4

This is to replace the last occurance in the string:

String testString = "It is a very good day isn't it or is it.Tell me?";
Console.WriteLine(Regex.Replace(testString, 
                  "(.*)(it)(.*)$", 
                  "$1THAT$3", 
                   RegexOptions.IgnoreCase));

If you can provide when the next to last should be replace, I can edit the answer to include that.

Chandu
  • 81,493
  • 19
  • 133
  • 134
  • I'm not sure what you mean. The next to last should be the second-to-last match. If you have haystack string: "Trying to find a particular string." - then the "next to last" would be the "i" in "particular". – jeffreypriebe Dec 30 '10 at 23:35
  • I understood what next to last means, but confused when you say last or next-to-last should be replaced. Do you mean last two occurances should be replaced? – Chandu Dec 30 '10 at 23:36
  • Fair enough. No, in "next to last" I just wanted the second to last to be replaced, but not the last. So, in the above Haystrick string: the "i" in "particular" _but not_ the "i" in "string". – jeffreypriebe Dec 30 '10 at 23:38
  • So if the text occurs twice or more then next to last shd be replaced, else the last occurance..Will update the answer... – Chandu Dec 30 '10 at 23:41
  • 1
    If I had known how to do "next to last" in regex, I would have done that, so it would be useful for using regex outside C# (where I can't use the MatchEvaluator delegate function). – jeffreypriebe Dec 31 '10 at 15:34
0

find in loop, save the last match position, then replace

Andriy Tylychko
  • 15,967
  • 6
  • 64
  • 112