簡體   English   中英

正則表達式替換 - 如何在不同字符串的多個位置替換相同的模式?

[英]Regex replace - how to replace same pattern in multiple places with different strings?

我有一個特殊的問題..!

我有一個字符串,在多個步驟中具有一些常量值。 例如,考慮以下刺痛。

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);
}

您需要確保找到的匹配數永遠不會超過數組的長度,如上所示。

編輯:在回應評論時,通過用以下代碼替換lambda,可以輕松地使用C#2.0:

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

你可以使用MatchEvaluator(一個被調用來執行每次替換的函數),這里有一些例子:

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

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

我認為Ahmad Mageed的第一個解決方案就是那個,因為array [index ++]在傳遞給rx.Replace方法時只被評估一次。

我也編譯它以驗證我是否正確理解它,並且確定它產生以下輸出:

你好value1在C#中,value1這個可能的值1是多少?

是否隨着框架的更高版本而改變了行為? 或者我錯誤地認為預期的輸出應該是:

你好value1在C#中,value2這個可能的值3怎么樣?...?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM