Regex replace multiple groups
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?
Solution 1:
Given a dictionary that defines your replacements:
IDictionary<string, string> map = new Dictionary<string, string>()
{
{"&","__amp"},
{"#","__hsh"},
{"1","5"},
{"5","6"},
};
You can use this both for constructing a Regular Expression, and to form a replacement for each match:
var str = "a1asda&fj#ahdk5adfls";
var regex = new Regex(String.Join("|",map.Keys));
var newStr = regex.Replace(str, m => map[m.Value]);
// newStr = a5asda__ampfj__hshahdk6adfls
Live example: http://rextester.com/rundotnet?code=ADDN57626
This uses a Regex.Replace
overload 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.Escape
and a minor change to the code above:
var str = "a1asda&fj#ahdk5adfls";
var regex = new Regex(String.Join("|",map.Keys.Select(k => Regex.Escape(k))));
var newStr = regex.Replace(str, m => map[m.Value]);
// newStr = a5asda__ampfj__hshahdk6adfls
Solution 2:
How about using string.Replace()
?
string foo = "a1asda&fj#ahdk5adfls";
string bar = foo.Replace("&","__amp")
.Replace("#","__hsh")
.Replace("5", "6")
.Replace("1", "5");