Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use Regular Expressions to replace a particular match (e.g "last" or "second to last")?

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?

like image 745
jeffreypriebe Avatar asked Dec 30 '10 22:12

jeffreypriebe


2 Answers

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?

like image 143
jeffreypriebe Avatar answered Nov 15 '22 05:11

jeffreypriebe


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.

like image 27
Chandu Avatar answered Nov 15 '22 04:11

Chandu