用正则表达式和我自己的参数替换字符串

时间:2013-11-20 15:47:23

标签: c# asp.net regex

在我的html中,我有这样的serval标记:

{PROP_1_1}, {PROP_1_2}, {PROP_37871_1} ...

实际上我用以下代码替换该标记:

htmlBuffer = htmlBuffer.Replace("{PROP_" + prop.PropertyID + "_1}", prop.PropertyDefaultHtml);

其中 prop 是自定义对象。但在这种情况下,它只影响以'_1'结尾的标记。我想将这个逻辑传播给所有其余的以“_X”结尾,其中X是数字。 我怎样才能实现regexp模式来实现这个目标?

2 个答案:

答案 0 :(得分:2)

您可以使用Regex.Replace()

Regex rgx = new Regex("{PROP_" + prop.PropertyID + "_\d+}");
htmlBuffer = rgx.Replace(htmlBuffer, prop.PropertyDefaultHtml);

答案 1 :(得分:2)

你可以做得更好,你可以在正则表达式中捕获两个标识符。这样你就可以遍历字符串中存在的引用并获取它们的属性,而不是循环遍历你拥有的所有属性,并检查字符串中是否有对它们的引用。

示例:

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);
});
相关问题