如何替换正则表达式

编程入门 行业动态 更新时间:2024-10-11 15:19:41
本文介绍了如何替换正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有这样的字符串Code =?And Desc =?或Qty =?。我想用正则表达式将重复到Code = @ 0 AND Desc = @ 1 OR Qty = @ 2。 ?可以更多,AND OR应该大写 我怎么能这样做。谢谢

解决方案

你还没有给出任何正则表达式,所以我在这个解决方案中选择了自己的(C#)。 一种可能的方法是在多个循环中替换标记。 C#正则表达式允许全局替换模式(这涵盖了和/或令牌)。要克服正则表达式无法计数的限制,您可以应用lambda表达式来计算在该lambda表达式之外定义的变量。 例如这个的原始版本可以用C#编码,如下所示:

static string 翻译(字符串输入) { string result = input; result = Regex.Replace(result, @ \b(和| or)\ b ,m = > m.Groups [ 1 ]。Value.ToUpper (), RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); int i = 0 ; result = Regex.Replace(结果, @ (\?),m = > @ +(我++)的ToString()); 返回结果; } 静态 void Main( string [] args) { string input = Code =?而Desc =?或Qty =?; Console.WriteLine( {0} - > {1},输入,翻译(输入)); }

你当然可以尝试将所有合并为一个正则表达式,但这会变得非常混乱。 干杯 Andi

Hi, I have string like this "Code = ? And Desc = ? Or Qty = ?". I would like to replce with regex to this "Code = @0 AND Desc = @1 OR Qty = @2". "?" can be more and AND OR shoul be Capitalize how can i do this. thanks

解决方案

You have not given any flavor of regex, so I chose my own (C#) in this solution. A possible approach is to replace tokens in multiple loops. The C# regex allows to globally replace patterns (this covers the and/or tokens). To overcome the limit that regex cannot count, you may apply lambda expressions that count up a variable that is defined outside of that lambda expression. E.g. a crude version of this could be coded in C# like this:

static string Translate(string input) { string result = input; result = Regex.Replace(result, @"\b(and|or)\b", m => m.Groups[1].Value.ToUpper(), RegexOptions.CultureInvariant|RegexOptions.IgnoreCase); int i = 0; result = Regex.Replace(result, @"(\?)", m => "@" + (i++).ToString()); return result; } static void Main(string[] args) { string input = "Code = ? And Desc = ? Or Qty = ?"; Console.WriteLine("{0} --> {1}", input, Translate(input)); }

You may of course try to merge all into one regex but that becomes quite messy. Cheers Andi

更多推荐

如何替换正则表达式

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

发布评论

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

>www.elefans.com

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