高级Regex.Replace处理

编程入门 行业动态 更新时间:2024-10-26 16:21:55
本文介绍了高级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处理

本文发布于:2023-11-04 00:42:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556485.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:高级   Regex   Replace

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!