How to check if String should be escaped in Java

235 views Asked by At

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?

1

There are 1 answers

0
WJS On

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