C# Regex replace using Dictionary

808 Views Asked by At

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.

1

There are 1 best solutions below

0
On BEST ANSWER

This has nothing to do with using a dictionary - it's simply because you're using characters with special meaning in regular expressions (+, ( and )) without quoting them. You'd get the same issue if you simply had value = Regex.Replace(input, "(", "%28")

You could use Regex.Escape to fix this though:

var regex = new Regex(String.Join("|",replacements.Keys.Select(Regex.Escape)));

Are you sure there isn't a built-in escaping method which does what you want though, e.g. a URL encoder? such as HttpUtility.UrlEncode? (I'm not an expert on URL encoding, and there may be some subtleties here - I would advise you to use an existing encoder rather than rolling your own though.)