正则表达式替换 - 如何在不同字符串的多个位置替换相同的模式?

时间:2010-01-18 05:50:36

标签: c# regex

我有一个奇怪的问题..!

我有一个字符串,其中包含多个常量值。例如,考虑以下刺痛。

string tmpStr = "Hello _tmp_ how is _tmp_ this possible _tmp_ in C#...?"

现在我想用字符串中的每个 tmp 替换存储在数组中的值,首先 tmp 保存数组[0],第二个 tmp 包含数组[1],依此类推......

知道如何实现这一目标......?我使用C#2.0

4 个答案:

答案 0 :(得分:4)

这个怎么样:

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替换为:#/ p>,这可以轻松地与C#2.0一起使用

string result = rx.Replace(input, delegate(Match m) { return array[index++]; });

答案 1 :(得分:2)

你可以使用MatchEvaluator(一个被调用来执行每次替换的函数),这里有一些例子:

http://msdn.microsoft.com/en-us/library/aa332127%28VS.71%29.aspx

答案 2 :(得分:1)

建议,你可以使用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] ) ;
}

答案 3 :(得分:1)

我认为Ahmad Mageed的第一个解决方案就是那个,因为array [index ++]在传递给rx.Replace方法时只被评估一次。

我也编译了它以验证我是否正确理解它,并且确定它产生以下输出:

  

Hello value1 value1是怎么回事   C#中的可能值1?

框架的更高版本的行为是否已更改?或者我错误地认为预期的输出应该是:

  

Hello value1 value2是怎么回事   C#中的可能值3?

相关问题