在java中替换字符串中的特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2608205/
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
replace special characters in string in java
提问by zahir
I want to know how to replace the string in Java.
我想知道如何替换 Java 中的字符串。
E.g.
例如
String a = "adf?sdf";
How can I replace and avoid special characters?
如何替换和避免特殊字符?
回答by Daniel Rikowski
It is hard to answer the question without knowing more of the context.
如果不了解更多上下文,就很难回答这个问题。
In general you might have an encoding problem. See The Absolute Minimum Every Software Developer (...) Must Know About Unicode and Character Setsfor an overview about character encodings.
一般来说,您可能有编码问题。有关字符编码的概述,请参阅每个软件开发人员 (...) 必须了解的关于 Unicode 和字符集的绝对最低要求。
回答by T.J. Crowder
You can use unicode escape sequences (such as \u201c
[an opening curly quote]) to "avoid" characters that can't be directly used in your source file encoding (which defaults to the default encoding for your your platform, but you can change it with the -encoding
parameter to javac
).
您可以使用 unicode 转义序列(例如\u201c
[开卷引号])来“避免”不能直接在源文件编码中使用的字符(默认为您平台的默认编码,但您可以更改它与-encoding
参数javac
)。
回答by BalusC
You can get rid of all characters outside the printable ASCII rangeusing String#replaceAll()
by replacing the pattern [^\\x20-\\x7e]
with an empty string:
您可以使用空字符串替换模式来删除可打印 ASCII 范围之外的所有字符:String#replaceAll()
[^\\x20-\\x7e]
a = a.replaceAll("[^\x20-\x7e]", "");
But this actually doesn't solveyour actualproblem. It's more a workaround. With the given information it's hard to nail down the root cause of this problem, but reading either of those articles must help a lot:
但这实际上并不能解决您的实际问题。这更像是一种解决方法。根据给定的信息,很难确定此问题的根本原因,但阅读其中任何一篇文章都会有很大帮助: