Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.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_Replace - Fatal编程技术网

C#正则表达式替换模板内容

C#正则表达式替换模板内容,c#,regex,replace,C#,Regex,Replace,在使用正则表达式在模板中用value替换关键字时,我测试了以下代码 string input = "Welcome {{friend}} Get my new {{id}} with {{anonymous}} People"; Dictionary<string, string> mydict = new Dictionary<string, string> (); mydict.Add("friend", "<&l

在使用正则表达式在模板中用value替换关键字时,我测试了以下代码

string input = "Welcome {{friend}} Get my new {{id}} with {{anonymous}} People";
            Dictionary<string, string> mydict = new Dictionary<string, string> ();
            mydict.Add("friend", "<<My Friend>>");
            mydict.Add("id", "<<Your ID>>");
            string pattern = @"(?<=\{{2})[^}}]*(?=\}{2})";// @"\{{2}^(.*?)$\}{2}";//"^[{{\\w}}]$";
            //var m = Regex.Match(input, @"\{{(.*)\}}");
            string regex = Regex.Replace(input, pattern, delegate(Match match) {
                string v = match.ToString();
                return mydict.ContainsKey(v) ? mydict[v] : v;

            });

            Console.WriteLine(regex);
string input=“欢迎{{{friend}}与{{anonymous}人一起获取我的新{{{id}}”;
Dictionary mydict=新字典();
mydict.Add(“friend”,”);
mydict.Add(“id”和“);

string pattern=@”(?大括号保留在原始文本中,因为您使用的是零宽度的前向和后向结构。这会使内容与
(?匹配。您可以使用简单的
{(.*)}
正则表达式,并使用组1 vlaue检查字典匹配:

string pattern = @"{{(.*?)}}";
string regex = Regex.Replace(input, pattern, delegate(Match match) {
     string v = match.Groups[1].Value;
     return mydict.ContainsKey(v) ? mydict[v] : v;
});
// => Welcome <<My Friend>> Get my new <<Your ID>> with anonymous People


请注意,
[^}}]
并不意味着匹配除
}
以外的任何文本,它只匹配除
}
以外的任何字符,与
[^}]
相同,因此在这种情况下,
*?
更可取。如果在
{
}之间只有字母、数字和下划线,则更可取

对于一些备选方案:@Fildor这是这些“最佳实践”之一"2009年提出的问题如果今天被问到的话,可能会被认为过于宽泛。@dasblinkenlight是的,但尽管如此,答案中仍有一些备选方案可能值得考虑。对该问题投反对票并给出正确的解决方案而不加评论是非常令人讨厌的。你至少应该说出你认为错误的地方。Hm、 Wiktor的回答是:“注意[^}}]并不意味着匹配除}}之外的任何文本,它只匹配除}之外的任何字符,与[^}]相同”——但这不值得dv,是吗?它仍然有效。
string pattern = @"{{(.*?)}}";
string regex = Regex.Replace(input, pattern, delegate(Match match) {
     string v = match.Groups[1].Value;
     return mydict.ContainsKey(v) ? mydict[v] : v;
});
// => Welcome <<My Friend>> Get my new <<Your ID>> with anonymous People
string regex = Regex.Replace(input, pattern, x =>
     mydict.ContainsKey(match.Groups[1].Value) ?
                mydict[match.Groups[1].Value] : match.Groups[1].Value;
});