How to escape all special character before Regex.Replace()

  • Thread starter Thread starter Sudip_inn
  • Start date Start date
S

Sudip_inn

Guest
I was facing a problem during regex replace. Regex.Replace() could not replace text and later i saw it was happening due to special chars in text.

This was the text which i was replacing.

"\"Operational Metrics~Copper C1 Cash Costs (US$/lb) - Lalor\"*\"Operational Metrics~Canadian Dollars (Canadian $/US$)\""

after replacing (, ) & $ chars then below code works

string mainstr = "\"" + "Operational Metrics~Copper C1 Cash Costs (US$/lb) - Lalor~9999" + "\"" + "*" + "\"" + "Operational Metrics~Canadian Dollars (Canadian $/US$)~9999" + "\"";
string replacesfrom = "\"" + "Operational Metrics~Copper C1 Cash Costs (US$/lb) - Lalor~9999" + "\"";
string replacesto = "A10";
string afterreplace = Regex.Replace(mainstr, replacesfrom.Replace("(", "\\(").Replace(")", "\\)").Replace("$", "\\$"), replacesto);


so i am looking for a generic routine which i will call and it will escape all the special chars. please share a routine which will escape all special chars in strings.

i read this links

Remove a list of special characters from string in C#

thanks

Continue reading...
 
Back
Top