空白字符序列到空白

sch*_*gel 5 java whitespace

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

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

aio*_*obe 3

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

纯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());
Run Code Online (Sandbox Code Playgroud)

使用 Apache Commons StringEscapeUtils:

import org.apache.commons.lang3.StringEscapeUtils;

...

System.out.println(StringEscapeUtils.unescapeJava(input));
Run Code Online (Sandbox Code Playgroud)