-1

I have a String which consists of backward slashes .

public static void main(String[] args) {

        String str = "\"json_value\": \"{\\\"screen\\\":\\\"SCR-3\\\",\\\"price\\\":\\\"200\\\",\\\"count\\\":\\\"0\\\",\\\"name\\\":\\\"Regular Cup, Delishy 50 Ml\\\",\\\"seat_num\\\":\\\"D12\\\",\\\"image\\\":\\\"http://192.168.2.46:8080/OrderSnacks/JSON_images/icecream_cup_vanilla.jpg\\\",\\\"quantity\\\":\\\"2\\\",\\\"orderid\\\":\\\"14070738\\\",\\\"itemid\\\":\\\"57\\\",\\\"vendor_id\\\":\\\"10101500072001001\\\",\\\"date_time\\\":\\\"13:07:38\\\",\\\"toppings\\\":[{\\\"name\\\":\\\"Quantity      1\\\",\\\"value\\\":[\\\"Honey with Chocolate Sauce  10 ML\\\"]},{\\\"name\\\":\\\"Quantity      2\\\",\\\"value\\\":[\\\"Honey with Chocolate Sauce  10 ML\\\"]}]}\",";


        str =   str.replaceAll("\\\\", "\\\\\\\\");

        System.out.println(str);

    }

Could anybody please let me know how to replace all backward slashes ??

I tried using str = str.replaceAll("\\", "\\\\"); , but its not replacing them .

user974802
  • 3,397
  • 10
  • 26
  • 29

3 Answers3

1
str =   str.replaceAll("\\\\", "");

Where is the problem???

laune
  • 31,114
  • 3
  • 29
  • 42
1
  String str = "\"json_value\": \"{\\\"screen\\\":\\\"SCR-3\\\",\\\"price\\\":\\\"200\\\",\\\"count\\\":\\\"0\\\",\\\"name\\\":\\\"Regular Cup, Delishy 50 Ml\\\",\\\"seat_num\\\":\\\"D12\\\",\\\"image\\\":\\\"http://192.168.2.46:8080/OrderSnacks/JSON_images/icecream_cup_vanilla.jpg\\\",\\\"quantity\\\":\\\"2\\\",\\\"orderid\\\":\\\"14070738\\\",\\\"itemid\\\":\\\"57\\\",\\\"vendor_id\\\":\\\"10101500072001001\\\",\\\"date_time\\\":\\\"13:07:38\\\",\\\"toppings\\\":[{\\\"name\\\":\\\"Quantity      1\\\",\\\"value\\\":[\\\"Honey with Chocolate Sauce  10 ML\\\"]},{\\\"name\\\":\\\"Quantity      2\\\",\\\"value\\\":[\\\"Honey with Chocolate Sauce  10 ML\\\"]}]}\",";


  str =   str.replaceAll("\\\\", "");

  System.out.println(str);


 output: 


 "json_value": "{"screen":"SCR-3","price":"200","count":"0","name":"Regular Cup, Delishy 50 Ml","seat_num":"D12","image":"http://192.168.2.46:8080/OrderSnacks/JSON_images/icecream_cup_vanilla.jpg","quantity":"2","orderid":"14070738","itemid":"57","vendor_id":"10101500072001001","date_time":"13:07:38","toppings":[{"name":"Quantity      1","value":["Honey with Chocolate Sauce  10 ML"]},{"name":"Quantity      2","value":["Honey with Chocolate Sauce  10 ML"]}]}",
learner
  • 365
  • 1
  • 3
  • 16
1

As replaceAll() treats the first argument as regex so you must double to escape the backslash

str = str.replaceAll("\\\\", "");

\ is a special char in java while using it in string.So to treat \ as normal character you need to place another \ to turn off its special meaning in regex. So to write \\ in regex you need to write it with four \

SparkOn
  • 8,806
  • 4
  • 29
  • 34