How to replace Backslash '\' with double Backslash in Dart?

5,535

The problem is that the string string does not contain any \

It would either need to be

String string = r"back\slash back\slash back\slash back\slash";

or

String string = "back\\slash back\\slash back\\slash back\\slash";

In your example there also is no need for RegExp. Just

String replaced = string.replaceAll(r'\', r'\\');

would do as well.

Share:
5,535
Shahzad Akram
Author by

Shahzad Akram

Updated on December 09, 2022

Comments

  • Shahzad Akram
    Shahzad Akram over 1 year

    How to replace a Single Backslash '\' in a String with double Backslash '\' ?

    I tried this, but its not working.

    main(){
    String string = "back\slash back\slash back\slash back\slash";
    String replaced = string.replaceAll(RegExp(r'\\'), '\\\\');
    print(replaced);
    }
    
    • Günter Zöchbauer
      Günter Zöchbauer about 5 years
      Do you get an error? What output do you get?
    • Shahzad Akram
      Shahzad Akram about 5 years
      No error , just I was unable to accomplish what I needed.
  • CoderBlue
    CoderBlue over 2 years
    This has to do with how Dart handles raw strings, for further explanation see How to Create A Raw String In Dart