高级Regex.Replace处理 [英] Advanced Regex.Replace handling

查看:99
本文介绍了高级Regex.Replace处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有MatchEvaluator委托的Regex来处理格式字符串,例如时间:%t,字节:%b将用时间戳替换%t,而%b用字节数替换。毋庸置疑,还有很多其他选择!

为此,我使用:

I am using a Regex with a MatchEvaluator delegate to process a format string, e.g. "Time: %t, bytes: %b" would replace the "%t" with a time stamp, and the "%b" with a bytes count. Needless to say, there are loads of other options!
To do this, I use:

Regex regex = new Regex("%((?<BytesCompleted>b)|(?<BytesRemaining>B)|(?<TimeStamp>t))");
string s = "%bhello%t(HH:MM:SS)%P";
string r = regex.Replace(s, new MatchEvaluator(ReplaceMatch));



and

string ReplaceMatch(Match m)
    {
    ... Handle the match replacement.
    }



如果我可以使用正则表达式组名称(甚至数字,我不是那么挑剔),那将是多么美好的事情在委托中,而不是与原始匹配进行比较,以找出这是匹配:


What would be nice is if I could use the Regex group name (or even the number, I'm not that fussy) in the delegate instead of comparing against the raw match to find out which match this is:

string ReplaceMatch(Match m)
    {
    ...
    case "%t":
    ...
    case "%b";
    ...
    }

非常丑陋;我想使用

Is pretty ugly; I would like to use

string ReplaceMatch(Match m)
    {
    ...
    case "BytesCompleted":
    ...
    case "TimeStamp":
    ...
    }

我无法通过调试器或谷歌看到任何明显的信息。任何想法?

I can't see anything obvious via the debugger, or via google. Any ideas?

推荐答案

我同意能够在交换机中使用组名称会很好;不幸的是,Group对象没有Name属性(它的基类Capture也没有)所以你能做的最好的是:



I agree it would be nice to be able to use the group name in the switch; unfortunately the Group object doesn't have a Name property (and neither does its base class Capture) so the best you'll be able to do is the following:

string ReplaceMatch(Match m)
    {
    if (m.Groups["BytesCompleted"].Success) ...
    else if (m.Groups["BytesRemaining"].Success) ...
    ...
    }


这篇关于高级Regex.Replace处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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