[英]Regex replace - how to replace same pattern in multiple places with different strings?
我有一个特殊的问题..!
我有一个字符串,在多个步骤中具有一些常量值。 例如,考虑以下刺痛。
string tmpStr = "Hello _tmp_ how is _tmp_ this possible _tmp_ in C#...?"
现在我想用存储在数组中的值替换字符串中的每个tmp ,首先tmp保存数组[0],第二个tmp保存数组[1],依此类推......
知道如何实现这一点......? 我使用C#2.0
这个怎么样:
string input = "Hello _tmp_ how is _tmp_ this possible _tmp_ in C#...?";
string[] array = { "value1", "value2", "value3" };
Regex rx = new Regex(@"\b_tmp_\b");
if (rx.Matches(input).Count <= array.Length)
{
int index = 0;
string result = rx.Replace(input, m => array[index++]);
Console.WriteLine(result);
}
您需要确保找到的匹配数永远不会超过数组的长度,如上所示。
编辑:在回应评论时,通过用以下代码替换lambda,可以轻松地使用C#2.0:
string result = rx.Replace(input, delegate(Match m) { return array[index++]; });
你可以使用MatchEvaluator(一个被调用来执行每次替换的函数),这里有一些例子:
http://msdn.microsoft.com/en-us/library/aa332127%28VS.71%29.aspx
建议,您可以使用string.Split()拆分“tmp”。 然后迭代分割项目列表并打印它们+数组值,例如只有伪代码的想法
string[] myarray = new string[] { 'val1', 'val2' };
string s = "Hello _tmp_ how is _tmp_ this possible _tmp_ in C#";
string[] items = s.Split("tmp");
for (int i = 0; i < items.Length; i++)
{
Console.WriteLine(parts[i] + myarray[i] ) ;
}
我认为Ahmad Mageed的第一个解决方案就是那个,因为array [index ++]在传递给rx.Replace方法时只被评估一次。
我也编译它以验证我是否正确理解它,并且确定它产生以下输出:
你好value1在C#中,value1这个可能的值1是多少?
是否随着框架的更高版本而改变了行为? 或者我错误地认为预期的输出应该是:
你好value1在C#中,value2这个可能的值3怎么样?...?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.