I am looking for an option to replace multiple characters of a string in one go. I'm trying to pass a string as a parameter for a URL which has special characters like," /,+,(,),#". So I need to do some encoding. In one of SO questions I came across this option Regex Replace
Below is the code
var input = "Product name A/C 2+2 (Mod #1)";
var space = "%20";
var slash = "%2F";
var plus = "%2B";
var open = "%28";
var hashV = "%23";
var close = "%29";
var replacements = new Dictionary<string,string>()
{
{" ",space},
{"/",slash},
{"+",plus},
{"(",open},
{"#",hashV},
{")",close}
};
var regex = new Regex(String.Join("|",replacements.Keys));
var replaced = regex.Replace(input,m => replacements[m.Value]);
Console.WriteLine(replaced);
I am getting the following error
System.ArgumentException: parsing " |/|+|(|#|)" - Quantifier {x,y} following nothing.
but if I comment out
plus, open and close I'm getting the output without any problem for those replacements.
Product%20name%20A%2FC%202+2%20(Mod%20%231)
Why replace doesn't work for these characters? Am I doing something wrong here?If there is any other way to solve this, I'm willing to try that too. But I want to understand this better.