'How to check if String should be escaped in Java
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?
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |