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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:13:05  来源:igfitidea点击:

Java: replace "[" "]" from text files strings

javaregexstringreplace

提问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 replaceAllinterprets 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 replaceinstead, 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 CharSequenceas an argument, rather than a String. But Stringimplements CharSequence)

(人们往往会错过这个方法,因为它接受 aCharSequence作为参数,而不是 a String。但String实现了CharSequence