Java:从文本文件字符串中替换“[”“]”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5058214/
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: replace "[" "]" from text files strings
提问by aneuryzm
I'm using
我正在使用
str.replaceAll("GeoData[", "");
to replace "[" symbol in some strings in my text file, but I get:
替换文本文件中某些字符串中的“[”符号,但我得到:
Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character class near index 7
GeoData[
^
at java.util.regex.Pattern.error(Pattern.java:1713)
how can I solve this ?
我该如何解决这个问题?
回答by Mark Byers
The method replaceAll
interprets the argument as a regular expression. In a regular expression you must escape [
if you want its literal meaning otherwise it is interpreted as the start of a character class.
该方法replaceAll
将参数解释为正则表达式。在正则表达式中,[
如果你想要它的字面意义,你必须转义,否则它被解释为字符类的开始。
str = str.replaceAll("GeoData\[", "");
If you didn't intend to use a regular expression then use replace
instead, as Bozho mentions in his answer.
如果您不打算使用正则表达式,请replace
改用,正如 Bozho 在他的回答中提到的那样。
回答by Bozho
Use the non-regex method String.replace(..)
: str.replace("GeoData[", "")
使用非正则表达式方法String.replace(..)
:str.replace("GeoData[", "")
(People tend to miss this method, because it takes a CharSequence
as an argument, rather than a String
. But String
implements CharSequence
)
(人们往往会错过这个方法,因为它接受 aCharSequence
作为参数,而不是 a String
。但String
实现了CharSequence
)