c# – 正则表达式替换 – 如何在不同字符串的多个位置替换相同的
发布时间:2020-12-15 08:17:25 所属栏目:百科 来源:网络整理
导读:我有一个特殊的问题..! 我有一个字符串,在多个步骤中具有一些常量值.例如,考虑以下刺痛. string tmpStr = "Hello _tmp_ how is _tmp_ this possible _tmp_ in C#...?" 现在我想用存储在数组中的值替换字符串中的每个tmp,首先tmp保存数组[0],第二个tmp保存数
我有一个特殊的问题..!
我有一个字符串,在多个步骤中具有一些常量值.例如,考虑以下刺痛. 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); } 您需要确保找到的匹配数永远不会超过数组的长度,如上所示. 编辑:响应评论,这可以很容易地使用C#2.0,用这个替换lambda: string result = rx.Replace(input,delegate(Match m) { return array[index++]; }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |