你如何使用正防爆pressions更换特定的匹配(例如"最后"或"倒数第二和QUOT;)? [英] How do you use Regular Expressions to replace a particular match (e.g "last" or "second to last")?

查看:149
本文介绍了你如何使用正防爆pressions更换特定的匹配(例如"最后"或"倒数第二和QUOT;)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更换一个(最后一个或下一个到最后一个)匹配的字符串。我有我的普通防爆pression已经和它的作品,但它替换所有的项目,那我也跑回来,通过更换一个项目。

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)

我想用MatchEvaluator但无法弄清楚如何。

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

任何帮助吗?

推荐答案

MatchEvaluator简直就是一个代表。你传递你的函数。

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);

这code跳过的最后一场比赛。你也可以检查下一个到最后一场比赛中以类似的方式。

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

也看到这个问题,关于如何使用MatchEvaluator信息如何MatchEvaluator的作品? (C#正则表达式替换)

Also see this question for more information on how to use MatchEvaluator: How does MatchEvaluator works? ( C# regex replace)

这篇关于你如何使用正防爆pressions更换特定的匹配(例如"最后"或"倒数第二和QUOT;)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆