为了

2011-09-02 34 views
2

替换占位符我有这样一个URL的一部分:为了

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

现在我想从一个字符串数组值替换所有的括号内。

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

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

更新:/不能用于分隔。只有占位符{...}应该被替换。

示例:/家庭/前{VALUE1} /和/ {anotherValue}

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

结果:/家庭/ 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; 

编辑: 谢谢德文德拉·查万D.和ipr101,

两种解决方案都是非常重要的!

+3

为什么正则表达式?难道你不能只是将字符串拆分为'/'并使用索引1和3? –

+0

你有代码示例和“之前”和“之后”字符串使问题更清晰吗? – CodeCaster

+0

使用该模式,在你的例子中'{[a-zA-Z0-1] *}'或'{\ w *}'会给出想要的结果。 –

回答

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]); 
} 
+0

'{'是量词分隔符,你应该在'\ {'和'\}'的问题中转义它。 – Abel

+0

在这种情况下([正则表达式引用](http://www.regular-expressions.info/reference.html))并非真正需要,但可以添加以便于清晰。 –

2

[a-zA-Z_]描述了一个字符类。对于话,你就必须在年底内a-zA-Z_添加*(任意数目的字符

然后,有“值1”拍摄的,你需要添加数支持:[a-zA-Z0-9_]*,可与总结:\w*

那么试试这个:{\w*}

但在C#替换,string.Split( '/'),还不如弗雷德里克提出的是更容易Have a look at this too

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] + "}"; 
}); 
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);