0

I have the following string and I want to escape backslash between the double quotes only. I tried doing this,

String s = "Hello\na = a.split(\"\n\")";
String tem = s.replaceAll("(?<=\")[^\\\\](?=\")", "\\\\");

But I get the following output,

# output
Hello
a = a.split("\")

I want it to be,

Hello
a = a.split("\n")

Any idea on this?

vardos
  • 334
  • 3
  • 13
  • 2
    Not saying it's impossible, but as a general rule, regex is not the right tool for parsing code. – shmosel Mar 06 '19 at 00:17

2 Answers2

1

Make it simple:

Assuming the backslash and double quotes, always preceding \n character

public static void main(String[] args) {
    String s = "Hello\na = a.split(\"\n\")";
    String tem = s.replaceAll("\\\"\\n\\\"", "\\\"\\\\n\\\"");
    System.out.println(tem);
}
0

How about something simpler ?

String s = "Hello\na = a.split(\"\n\")";
String tem = s.replaceAll("(\\)(?=\")", "\\\\");    

You can try it here or here

vfalcao
  • 332
  • 1
  • 3
  • 12