简体   繁体   English

转义字符串中的字符

[英]Escaping characters in a string

I have a string that contains escaped characters: 我有一个包含转义字符的字符串:

String myString = "I\\nam\\na\\nmultiline\\nstring\\twith\\ttabs";

I would like to convert the escaped characters so that it would output: 我想转换转义的字符,以便输出:

System.out.println(myConvertedString);
I
am
a
multiline
string    with    tabs

Is there any standard function (maybe Guava) that does this? 是否有执行此操作的任何标准功能(也许是Guava)?

If you have received the exception from a stack trace, the only escaped characters are probably \\n and \\t , in which case: 如果您从堆栈跟踪中收到异常,则唯一的转义字符可能是\\n\\t ,在这种情况下:

String converted = input.replace("\\n", "\n").replace("\\t", "\t");

If there can be more than that I think you'll have to list all the possibilities. 如果还有更多,我认为您必须列出所有可能性。

StringEscapeUtils in the apache commons library has many methods that will escape, or unesecape a string as required. apache commons库中的StringEscapeUtils具有许多可以转义或根据需要取消转义字符串的方法。

StringEscapeUtils.escapeJava(someString);
StringEscapeUtils.unescapeJava(someOtherString);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM