I would like to use regular expressions to replace multiple groups with corresponding replacement string.
Replacement table:
"&"->"__amp""#"->"__hsh""1"->"5""5"->"6"
For example, for the following input string
"a1asda&fj#ahdk5adfls"
the corresponding output string is
"a5asda__ampfj__hshahdk6adfls"
Is there any way to do that?
Given a dictionary that defines your replacements:
You can use this both for constructing a Regular Expression, and to form a replacement for each match:
Live example: http://rextester.com/rundotnet?code=ADDN57626
This uses a
Regex.Replaceoverload which allows you to specify a lambda expression for the replacement.It has been pointed out in the comments that a find pattern which has regex syntax in it will not work as expected. This could be overcome by using
Regex.Escapeand a minor change to the code above: