Whitespace char sequence to Whitespace

java, whitespace

Solution

No, once compiled, `"\\n"` has nothing to do with `"\n"` afaik. I would suggest doing something as follows:

Pure Java:

String input = "\\n hello \\t world \\r";

String from = "ntrf";
String to   = "\n\t\r\f";
Matcher m = Pattern.compile("\\\\(["+from+"])").matcher(input);
StringBuffer sb = new StringBuffer();
while (m.find())
    m.appendReplacement(sb, "" + to.charAt(from.indexOf(m.group(1))));
m.appendTail(sb);

System.out.println(sb.toString());

Using Apache Commons StringEscapeUtils:

import org.apache.commons.lang3.StringEscapeUtils;

...

System.out.println(StringEscapeUtils.unescapeJava(input));

Problem

I'm searching for a solution to convert char sequences like '\''n' to '\n' without writing a switch for all possible whitespace commands like ('\t', '\r', '\n', etc.) Is there something build in or a clever trick to do that?

Original source