ane*_*yzm 6 java regex string replace
我正在使用
str.replaceAll("GeoData[", "");
Run Code Online (Sandbox Code Playgroud)
替换我的文本文件中的某些字符串中的"["符号,但我得到:
Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character class near index 7
GeoData[
^
at java.util.regex.Pattern.error(Pattern.java:1713)
Run Code Online (Sandbox Code Playgroud)
我该怎么解决这个问题?
Mar*_*ers 17
该方法replaceAll将参数解释为正则表达式.在正则表达式中,[如果您想要其字面意义,则必须转义,否则它将被解释为字符类的开头.
str = str.replaceAll("GeoData\\[", "");
Run Code Online (Sandbox Code Playgroud)
如果你不打算使用正则表达式,那么请使用replace,正如Bozho在他的回答中提到的那样.
Boz*_*zho 11
使用非正则表达式方法String.replace(..):str.replace("GeoData[", "")
(人们往往会错过这种方法,因为它需要一个CharSequence参数,而不是一个String.但是String实现CharSequence)