Daniel Rikowski Daniel Rikowski - 1 month ago 10
Java Question

Is there a Java function which parses escaped characters?

I'm looking for a built-in Java functions which for example can convert

"\\n"
into
"\n"
.

Something like this:

assert parseFunc("\\n") = "\n"


Or do I have to manually search-and-replace all the escaped characters?

Answer

Just use the strings own replaceAll method.

result = myString.replaceAll("\\n", "\n");

However if you want match all escape sequences then you could use a Matcher. See http://www.regular-expressions.info/java.html for a very basic example of using Matcher.

Pattern p = Pattern.compile("\\(.)");
Matcher m = p.matcher("This is tab \\t and \\n this is on a new line");
StringBuffer sb = new StringBuffer();
while (m.find()) {
   String s = m.group(1);
   if (s == "n") {s = "\n"; }
   else if (s == "t") {s = "\t"; } 
   m.appendReplacement(sb, s);
}
m.appendTail(sb);
System.out.println(sb.toString());

You just need to make the assignment to s more sophisticated depending on the number and type of escapes you want to handle. (Warning this is air code, I'm not Java developer)