[英]C# Regex Replacing Template content
在使用Regex将模板中的关键字替换为值时,我测试了以下代码。
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);
大括号仍然保留在输出中,这是不希望的
我需要<<My Friend>>
而不是{{ <<My Friend>> }}
。 谢谢您的建议。
大括号保留在原始文本中,因为您使用的是零宽度前瞻和后向构造。 这就使由(?<=...)
和(?=...)
匹配的内容超出了正则表达式的捕获值,因此不会被替换。
要解决此问题,请从正则表达式中删除前瞻和后视,在标签文本周围放置一个捕获组,然后使用它来搜索替换字典:
string pattern = @"\{{2}([^}}]*)\}{2}";
...
var v = match.Group[1].Value;
return mydict.ContainsKey(v) ? mydict[v] : v;
您可以使用简单的{{(.*?)}}
正则表达式,并使用第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
带有lambda表达式的相同代码:
string regex = Regex.Replace(input, pattern, x =>
mydict.ContainsKey(match.Groups[1].Value) ?
mydict[match.Groups[1].Value] : match.Groups[1].Value;
});
参见C#演示 。
注意[^}}]
并不意味着匹配}}
以外的任何文本 ,它仅匹配}
以外的任何字符,与[^}]
相同,所以.*?
在这种情况下最好。 甚至\\w+
如果在{{
和}}
之间只有字母,数字和下划线。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.