[英]c# regex replace problems with dynamic matches?
So I have a long string where I have "reserved words" that I need to be replaced by their value from the db. 因此,我有一个很长的字符串,其中有“保留字”,需要用数据库中的值替换它们。
eg.
string text = "You're salary for the month of ((month)) is ((salary))
Now what I did was to match each and every reserved word and then search through my dataset and then replace those with their value 现在我要做的是匹配每个保留字,然后搜索我的数据集,然后将其替换为它们的值
Regex ex = new Regex(@"(?<=\(\().*?(?=\)\))");
foreach(Match match in ex.Matches(body)){
string valuefromset = values.FirstOrDefault(val => val.Variable == match.Value).Value;
var pattern = @"(("+match.Value+"))";
body = Regex.Replace(body, pattern, valuefromset, RegexOptions.IgnoreCase);
}
}
Now what's happening is this 现在发生了什么事
text = "You're salary for the month of ((April)) is (($10000))";
I wasn't sure as to why the pattern will just get the words and not the tags. 我不确定为什么该模式只会得到单词而不是标签。 Should I be using another regex but with the specific value? 我应该使用其他正则表达式但具有特定值吗? Having the specific reserved word is significant in the pattern that's why I used that, wasn't really sure what i was doing. 在我使用该模式的过程中,拥有特定的保留字非常重要,因此我不确定自己在做什么。
Any help is appreciated. 任何帮助表示赞赏。 Thanks!!! 谢谢!!!
Thats because you don't escape the slashes in the replace regex 那是因为您无法在替换正则表达式中转义斜线
var pattern = @"(("+match.Value+"))";
^^ ^^
you are not matching them, you create two groups. 您不匹配它们,则创建两个组。 Try this: 尝试这个:
var pattern = @"\(\("+match.Value+"\)\)";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.