Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/303.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#正则表达式替换标记化字符串_C#_Regex - Fatal编程技术网

C#正则表达式替换标记化字符串

C#正则表达式替换标记化字符串,c#,regex,C#,Regex,我有一根像这样的线: string s = "{{hello {{User.Name}},thanks for your buying in {{Shop}}"; 我怎样才能使用like: IDictionary<string,string> vals=new Dictionary<string,string>() { {"User.Name","Jim" }, {"Shop",

我有一根像这样的线:

       string s = "{{hello {{User.Name}},thanks for your buying in {{Shop}}";
我怎样才能使用like:

       IDictionary<string,string> vals=new Dictionary<string,string>()
        {
            {"User.Name","Jim" },
            {"Shop","NewStore" }
        }
        string result= Regex.Replace(s, @"{{.+}}", m => vals[m.Groups[1].Value]);
IDictionary vals=new Dictionary()
{
{“User.Name”,“Jim”},
{“商店”、“新闻商店”}
}
字符串result=Regex.Replace(s,@“{.+}”,m=>vals[m.Groups[1].Value]);

但这不是因为正则表达式将匹配整个字符串(前两个{{实际上是字符串,不是令牌)

我假设
vals
字典中的所有键都不包含
{
}
字符

要处理这种情况,请不要在
{.+}
匹配中使用
接受除
\n
以外的任何单个字符(如果是正则表达式代码)

替换为
[^\{}]
,该字符与
{
}
以外的任何字符匹配
您应该在regex函数中转义
{
}
,因为它们在regex中有特殊的含义。有些情况下,regex将它们视为文字字符,但在其他情况下不处理

要有m.Groups[1],必须将
[^\{}]+
包装在

最后,为了避免异常,请在替换之前检查字典键是否包含由上述正则表达式函数找到的字符串

您的代码可以如下所示:

string s = "{{hello {{User.Name}}, thanks for your buying in {{Shop}}. This {{Tag}} is not found";

IDictionary<string, string> vals = new Dictionary<string, string>()
{
    {"User.Name","Jim" },
    {"Shop","NewStore" }
};

string result = Regex.Replace(s, @"\{\{([^\{\}]+)\}\}",
    m => vals.ContainsKey(m.Groups[1].Value) ? vals[m.Groups[1].Value] : m.Value);
Console.WriteLine(result);

传统的线程在匹配嵌套的成对标签……通过明确你认为什么是有效匹配和限制可能嵌套,你将给某人提供具体的答案在你的情况下。谢谢!这非常有帮助!
{{hello Jim, thanks for your buying in NewStore. This {{Tag}} is not found