爲了

2011-09-02 39 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);