【问题标题】:Incremental character replacement using regex使用正则表达式进行增量字符替换
【发布时间】:2016-09-28 10:43:31
【问题描述】:

你好,我有一个类似下面的字符串

Some text here -   
~XY*901*000000001~MLC*~XY*901*000000005~MLC*~XY*901*0000000010~MLC* 
Some text here

我想拥有它——

Some text here 
~XY*901*000000001~MLC*~XY*901*000000002~MLC*~XY*901*000000003~MLC* 
Some text here 

说明:~XY*901*~MLC* 之间的所有内容都应该从 1 开始加一。

如何使用 Regex Match Evaluator 实现?

【问题讨论】:

  • 我想知道如果你有5 变成210 变成3,你如何增加这些数字。
  • @WiktorStribiżew 我们可以使用 C# 匹配评估器,只是我无法弄清楚。
  • 投反对票的人请对投反对票发表评论。当我的问题被明确陈述时,这很荒谬,我不知道如何比这更好地解释它
  • 这个问题可能是stackoverflow.com/questions/2587866/…的欺骗
  • 不,不是,我仍在努力,如果我成功了,会作为答案发布

标签: c# regex pattern-matching


【解决方案1】:

有点兰巴达。嗯,我的意思是 lambda。

var input = @"Some text here -
~XY*901*000000001~MLC*~XY*901*000000005~MLC*~XY*901*0000000010~MLC*
More text here";

var reg = new System.Text.RegularExpressions.Regex(@"(~XY\*901\*)[0-9]+(~MLC\*)");

int i = 1;
var result = reg.Replace(input, m => m.Groups[1] + i++.ToString("D9") + m.Groups[2]);

Console.WriteLine(result);

正则表达式替换循环通过正则表达式的匹配。 同时增加整数。

输出:

Some text here -
~XY*901*000000001~MLC*~XY*901*000000002~MLC*~XY*901*000000003~MLC*
More text here 

【讨论】:

  • 你这个摇滚伙伴,当我正要发布我自己的答案时,我得到了你的感谢
猜你喜欢
  • 2011-03-12
  • 1970-01-01
  • 1970-01-01
  • 2015-11-03
  • 2015-11-30
  • 1970-01-01
  • 1970-01-01
  • 2015-02-27
相关资源
最近更新 更多