按顺序替换占位符

时间:2011-09-02 12:14:55

标签: c# .net regex

我有这样一个网址的一部分:

/home/{value1}/something/{anotherValue}

现在我想用括号数组中的值替换括号之间的所有内容。

我尝试了这个RegEx模式:\{[a-zA-Z_]\}但它不起作用。

稍后(在C#中)我想用数组的第一个值替换第一个匹配,用第二个替换第二个匹配。

更新:/不能用来分开。只应替换占位符{...}。

示例:/ home / before {value1} /和/ {anotherValue}

字符串数组:{“Tag”,“1”}

结果:/ home / beforeTag /和/ 1

我希望它可以这样工作:

string input = @"/home/before{value1}/and/{anotherValue}";
string pattern = @"\{[a-zA-Z_]\}";
string[] values = {"Tag", "1"};

MatchCollection mc = Regex.Match(input, pattern);        
for(int i, ...)
{
    mc.Replace(values[i];
}        
string result = mc.GetResult;

编辑: 谢谢Devendra D. Chavan和ipr101,

两种解决方案都很棒!

4 个答案:

答案 0 :(得分:3)

您可以尝试使用此代码片段

// Begin with '{' followed by any number of word like characters and then end with '}'
var pattern = @"{\w*}"; 
var regex = new Regex(pattern);

var replacementArray = new [] {"abc", "cde", "def"};
var sourceString = @"/home/{value1}/something/{anotherValue}";

var matchCollection = regex.Matches(sourceString);
for (int i = 0; i < matchCollection.Count && i < replacementArray.Length; i++)
{
    sourceString = sourceString.Replace(matchCollection[i].Value, replacementArray[i]);
}

答案 1 :(得分:2)

[a-zA-Z_]描述了一个字符类。对于文字,您最后必须添加*a-zA-Z_中的任意数量的字符。

然后,要捕获“value1”,您需要添加数字支持:[a-zA-Z0-9_]*,可以使用以下内容进行汇总:\w*

所以试试这个:{\w*}

但是为了替换C#,像Fredrik提议的那样,string.Split('/')可能会更容易。 Have a look at this too

答案 2 :(得分:1)

您可以使用委托,类似这样 -

string[] strings = {"dog", "cat"};
int counter = -1;
string input = @"/home/{value1}/something/{anotherValue}";
Regex reg = new Regex(@"\{([a-zA-Z0-9]*)\}");
string result = reg.Replace(input, delegate(Match m) {
    counter++;
    return "{" + strings[counter] + "}";
});

答案 3 :(得分:0)

我的两分钱:

// input string     
string txt = "/home/{value1}/something/{anotherValue}";

// template replacements
string[] str_array = { "one", "two" };

// regex to match a template
Regex regex = new Regex("{[^}]*}");

// replace the first template occurrence for each element in array
foreach (string s in str_array)
{
    txt = regex.Replace(txt, s, 1);
}

Console.Write(txt);
相关问题