Space char sequences to space

I am looking for a solution to convert char sequences like '\' 'n' to '\ n' without writing a switch for all possible commands as spaces, such as ('\ t', '\ r', '\ n' etc.)

Is there anything to build or a clever trick?

+5
source share
1 answer

No, after compilation "\\n"it 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));
+3
source

All Articles