简体   繁体   English

Java:从文本文件字符串中替换“[”“]”

[英]Java: replace “[” “]” from text files strings

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 ? 我该怎么解决这个问题?

The method replaceAll interprets the argument as a regular expression. 方法replaceAll将参数解释为正则表达式。 In a regular expression you must escape [ if you want its literal meaning otherwise it is interpreted as the start of a character class. 在正则表达式中,您必须转义[如果您想要它的字面含义,否则它将被解释为字符类的开头。

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在他的回答中提到的那样。

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 ) (人们倾向于错过这种方法,因为它将CharSequence作为参数,而不是String 。但String实现了CharSequence

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM