开发者

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.

R开发者_StackOverflow社区egex.Replace(BaseString, MatchString, ReplacementString)

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

Any help?


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?


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜