Java replaceAll() 方法来转义特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18183694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java replaceAll() method to escape special characters
提问by Abhishek Goel
I am using java replaceAll()
method to escape new line characters
我正在使用 javareplaceAll()
方法来转义换行符
String comment = "ddnfa \n \r \tdnfadsf ' \r t ";
comment = comment.replaceAll("(\n|\r|\t)","\\");
System.out.println(comment);
But the above code is still inserting new line.
但是上面的代码仍然插入新行。
Is there a way to output the comment exactly the same (i.e. with \n
and \r
instead of inserting new line)?
有没有办法输出完全相同的注释(即使用\n
和\r
而不是插入新行)?
UPDATE:
更新:
I ended up using:
我最终使用了:
comment = comment.replaceAll("\n","\\n")
.replaceAll("\r","\\r")
.replaceAll("\t","\\t");
回答by x4rf41
you will have to do it character by character:
您必须逐个执行此操作:
comment = comment.replaceAll("\n","\\n");
comment = comment.replaceAll("\r","\\r");
comment = comment.replaceAll("\t","\\t");
another solution is to escape the String as a Java String using this function:
另一个解决方案是使用此函数将字符串转义为 Java 字符串:
comment = org.apache.commons.lang.StringEscapeUtils.escapeJava(comment);
This will make the String look exactly like the String in the Java Code, but it will also show other escape sequences (like \\
, \"
etc).
But maybe thats exactly what you want
这将使字符串看起来就像字符串中的Java代码,但它也会显示其他转义序列(如\\
,\"
等)。但也许这正是你想要的
回答by Joni
You'll have to go one-by-one, since the new-line character U+000A has nothing to do with the two-character escape sequence \n
:
您必须一一进行,因为换行符 U+000A 与两个字符的转义序列无关\n
:
comment = comment.replaceAll("\n","\\n");
comment = comment.replaceAll("\r","\\r");
comment = comment.replaceAll("\t","\\t");
回答by AJJ
Try this..
尝试这个..
comment.replaceAll("(\n)|(\r)|(\t)", "\n");
回答by cl-r
It is a \
problem, simplify like this :
这是一个\
问题,简化成这样:
comment = comment.replaceAll("(\n|\r|\t)", "");
output :
输出 :
ddnfa dnfadsf ' t
回答by falsetru
Hard way: using Matcher
困难的方法:使用 Matcher
String comment = "ddnfa \n \r \tdnfadsf ' \r t ";
Map<String,String> sub = new HashMap<String,String>();
sub.put("\n", "\\n");
sub.put("\r", "\\r");
sub.put("\t", "\\t");
StringBuffer result = new StringBuffer();
Pattern regex = Pattern.compile("\n|\r|\t");
Matcher matcher = regex.matcher(comment);
while (matcher.find()) {
matcher.appendReplacement(result, sub.get(matcher.group()));
}
matcher.appendTail(result);
System.out.println(result.toString());
prints
印刷
ddnfa \n \r \tdnfadsf ' \r
回答by user4881671
Why you dont use Matcher.quoteReplacement(stringToBeReplaced);
?
你为什么不使用Matcher.quoteReplacement(stringToBeReplaced);
?