[英]Replace string with regular expression and my own parameter
在我的HTML中,我有這樣的serval標記:
{PROP_1_1}, {PROP_1_2}, {PROP_37871_1} ...
實際上我用以下代碼替換該標記:
htmlBuffer = htmlBuffer.Replace("{PROP_" + prop.PropertyID + "_1}", prop.PropertyDefaultHtml);
prop是一個自定義對象。 但在這種情況下,它只影響以'_1'結尾的標記。 我想將這個邏輯傳播給所有其余的以“_X”結尾,其中X是數字。 我怎樣才能實現正則表達式模式來實現這一目標?
您可以使用Regex.Replace()
:
Regex rgx = new Regex("{PROP_" + prop.PropertyID + "_\d+}");
htmlBuffer = rgx.Replace(htmlBuffer, prop.PropertyDefaultHtml);
你可以做得更好,你可以在正則表達式中捕獲兩個標識符。 這樣,您可以循環遍歷字符串中存在的引用並獲取這些引用的屬性,而不是循環遍歷您擁有的所有屬性,並檢查字符串中是否有對它們的引用。
例:
htmlBuffer = Regex.Replace(htmlBuffer, @"{PROP_(\d+)_(\d+)}", m => {
int id = Int32.Parse(m.Groups[1].Value);
int suffix = Int32.Parse(m.Groups[2].Value);
return properties[id].GetValue(suffix);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.