Replacing Regex matches using lambda expression

那年仲夏 提交于 2019-11-27 07:17:38

问题


I'm looking for a simple regex find and replace solution were I can just provide a lambda expression for replacing each matches. E.g:

regex.MatchReplace(text, match => "replacement string");

This way I can create my own logic for generating the replacement string which may involve invoking various methods etc. i.e. things you can't do with substitution patterns. Anyone know how I can accomplish this?


回答1:


Regex already has one. For ex,

string input="abc123def";
var output = Regex.Replace(input, @"\d", m=>(m.Value[0]-'0'+ 5).ToString());
Console.WriteLine(output);

OUTPUT: abc678def




回答2:


Please have a look at the following:

https://msdn.microsoft.com/en-GB/library/bb383977.aspx

You can define an extension method for the RegEx class which will allow you to specify an Action<> as an argument.



来源:https://stackoverflow.com/questions/31326451/replacing-regex-matches-using-lambda-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!