空白字符序列到空白

时间:2012-05-17 08:19:01

标签: java whitespace

我正在寻找一种解决方案,将'\''''之类的字符序列转换为'\ n',而无需为所有可能的空白命令编写开关,例如('\ t','\ r','\ n '等等。)

有没有内置的东西或聪明的技巧呢?

1 个答案:

答案 0 :(得分:3)

不,编译后,"\\n""\n" afaik无关。我建议做一些如下事情:

纯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());

使用Apache Commons StringEscapeUtils:

import org.apache.commons.lang3.StringEscapeUtils;

...

System.out.println(StringEscapeUtils.unescapeJava(input));
相关问题