使用哈希表

时间:2017-02-08 09:36:44

标签: c# regex

我的文字占位符如下

  

“我的名字是| @ NAME @ |我的年龄是| @ AGE @ |”

我有< string,string>包含每个占位符的字典及其基于该字典的值

所以我需要用值

替换每个占位符

我尝试了这个,但它不起作用

 Regex regex = new Regex(@"\|@([^\@|]+)\}", RegexOptions.Compiled);

 string newStr  = regex.Replace(
     originalString, 
     delegate(Match match) 
     {
         return placeholder[match.Groups[1].Value];
     });

1 个答案:

答案 0 :(得分:3)

在正则表达式中,\}与输入中缺少的}匹配。

您需要使用

@"\|@(.+?)@\|"

请参阅regex demo

<强>详情:

  • \|@ - |@字符序列
  • (.+?) - 捕获第1组匹配除换行符之外的任何一个或多个字符
  • @\| - @|字符序列。

在代码中,您可以使用

string newStr  = Regex.Replace(
            originalString, 
            @"\|@(.+?)@\|",
            match => placeholder.ContainsKey(match.Groups[1].Value) ?
                     placeholder[match.Groups[1].Value] : match.Value
          );