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

  • Question

  • 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

    https://stackoverflow.com/questions/22830918/remove-a-list-of-special-characters-from-string-in-c-sharp

    thanks

    Friday, November 13, 2020 12:13 PM

Answers

  • Try this line:

    string afterreplace = Regex.Replace( mainstr, Regex.Escape( replacesfrom ), replacesto );

    Or maybe describe the problem to be solved.


    • Edited by Viorel_MVP Friday, November 13, 2020 2:00 PM
    • Marked as answer by Sudip_inn Saturday, November 14, 2020 6:35 PM
    Friday, November 13, 2020 1:59 PM
  • Regex.Escape( ) will escape all special characters automatically ?


    Yes, it replaces the special characters (listed in documentation for Regex.Escape) automatically.


    • Marked as answer by Sudip_inn Monday, November 16, 2020 10:05 AM
    Saturday, November 14, 2020 6:40 PM

All replies

  • Try this line:

    string afterreplace = Regex.Replace( mainstr, Regex.Escape( replacesfrom ), replacesto );

    Or maybe describe the problem to be solved.


    • Edited by Viorel_MVP Friday, November 13, 2020 2:00 PM
    • Marked as answer by Sudip_inn Saturday, November 14, 2020 6:35 PM
    Friday, November 13, 2020 1:59 PM
  • Regex.Escape( ) will escape all special characters automatically ?

    i used it and works like a charm.

    Thanks you so much Sir.


    • Edited by Sudip_inn Saturday, November 14, 2020 6:36 PM
    Saturday, November 14, 2020 5:55 PM
  • Regex.Escape( ) will escape all special characters automatically ?


    Yes, it replaces the special characters (listed in documentation for Regex.Escape) automatically.


    • Marked as answer by Sudip_inn Monday, November 16, 2020 10:05 AM
    Saturday, November 14, 2020 6:40 PM