简体   繁体   English

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

[英]C# regex replace tokenized string

I have a string like ths: 我有一个像这样的字符串:

       string s = "{{hello {{User.Name}},thanks for your buying in {{Shop}}";

And how can I use 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]);

but it doesn't because regex will match the whole string (The first two {{ actually in string,not token ) 但这不是因为正则表达式将匹配整个字符串(前两个{{实际上是字符串,不是token)

I assume all keys int your vals dictionary don't contain { and } character. 我假设int vals字典中的所有键都不包含{}字符。

To deal with this case, dont use . 要处理这种情况,请不要使用. in the {{.+}} match. {{.+}}匹配中。 . accept any single character except \\n (in case your regex code). 接受\\n以外的任何单个字符(以防您的正则表达式代码)。

Replace . 更换. with [^\\{\\}] , which match any character except { and } . [^\\{\\}]匹配,匹配{}以外的任何字符。
And you should escape { and } in your regex function, because they have special meaning in Regex. 并且您应该在正则表达式函数中转义{} ,因为它们在正则表达式中具有特殊含义。 Some cases Regex treat them as literal charater, but not in other cases. 某些情况下,正则表达式将它们视为字面意义,但在其他情况下则不然。

To have m.Groups[1], you have to wrap [^\\{\\}]+ inside ( and ) . 要拥有m.Groups [1],您必须将[^\\{\\}]+包装在()

Finally, to avoid exception, check if your dictionary keys contain a string found by above Regex function before replace it. 最后,为避免出现异常,请在替换字典键之前,检查其字典键是否包含上述Regex函数找到的字符串。

Your code can be like bellow: 您的代码可以像下面这样:

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);

Output: 输出:

{{hello Jim, thanks for your buying in NewStore. This {{Tag}} is not found

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM