如何使用正则表达式替换特定匹配(例如"last"或"倒数第二")?

jef*_*ebe 5 .net c# regex matchevaluator

我正在尝试替换字符串中的单个(last或next-to-last)匹配.我已经有了我的正则表达式并且它有效,但它取代了所有项目,然后我必须重新运行并替换单个项目.

Regex.Replace(BaseString, MatchString, ReplacementString)

我想使用MatchEvaluator,但无法弄清楚如何.

有帮助吗?

jef*_*ebe 13

MatchEvaluator只是一个委托.你传递了你的功能.

在您的情况下,使用类似于:

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

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

此代码会跳过最后一场比赛.您也可以以类似的方式检查倒数第二场比赛.

另请参阅此问题以获取有关如何使用MatchEvaluator的更多信息:Regex.Replace中的MatchEvaluator如何工作?