0

I want to check if a specific String should be escaped before really performing any escaping mechanism. for example: if the String is "msg\t" so I want to escape it but if the String is "msg\\t" meaning it is already escaped or for example "msg" meaning no need to escape at all.

is there a way to check is easily?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Tal Levi
  • 363
  • 1
  • 6
  • 22

1 Answers1

0

Based on your description, this should work. It uses a map to map the actual value to the letter that represents it. Additional logic would need to be incorporated to escape backslashes since they serve a dual purpose which would need to be processed separately.

Map<String,String> esc = Map.of( "\t", "t", "\n", "n", "\f", "f");
String s = "msg\n msg\\t msg\\n msg\n";

for (Entry<String,String> e : esc.entrySet()) {
    s = s.replace(e.getKey(), "\\"+e.getValue());
}

System.out.println(s);

Prints

msg\n msg\t msg\n msg\n
WJS
  • 36,363
  • 4
  • 24
  • 39