簡體   English   中英

按順序替換占位符

[英]Replace placeholders in order

我有一部分網址是這樣的:

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

現在我想用字符串數組中的值替換括號之間的所有內容。

我嘗試了以下RegEx模式: \\{[a-zA-Z_]\\}但是它不起作用。

稍后(在C#中),我想將第一個匹配項替換為數組的第一個值,將第二個替換為第二個。

更新:/不能用於分隔。 僅占位符{...}應該被替換。

示例:/ home /之前{value1} /和// {anotherValue}

字符串數組:{“ Tag”,“ 1”}

結果:/ home / beforeTag / and / 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,

兩種解決方案都很棒!

您可以嘗試以下代碼片段,

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

[a-zA-Z_]描述一個字符類。 對於單詞,您必須在末尾添加*a-zA-Z_任意數量的字符。

然后,要捕獲'value1',您需要添加數字支持: [a-zA-Z0-9_]* ,可以將其概括為: \\w*

因此,請嘗試以下操作: {\\w*}

但是對於用C#替換,如Fredrik所建議的那樣,string.Split('/')可能會更容易。 也看看這個

您可以使用一個代表,像這樣-

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

我的兩分錢:

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

暫無
暫無

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

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