Java - 在正则表达式中转义元字符 [ 和 ]
我试图替换另一个字符串中第一次出现的字符串“[]”:
aString.replaceFirst(“[]”,“blah”);
我收到错误: java.util.regex.PatternSyntaxException:索引 1 [] [ 和 ] 附近的未封闭字符类
显然是元字符,但是当我尝试用 \ 转义它们时 eclipse 抱怨它不是有效的转义序列。
我看过但找不到,我错过了什么?
谢谢
I am attempting to replace the first occurrence of the string "[]" in another string:
aString.replaceFirst("[]", "blah");
I get the error:
java.util.regex.PatternSyntaxException: Unclosed character class near index 1 []
[ and ] are obviously metacharacters, however when I try to escape them with a \
eclipse complains that it is not a valid escape sequence.
I've looked but couldn't find, what am I missing?
Thank You
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正则表达式模式使用
\
作为转义字符,Java 也是如此。因此,要在正则表达式模式中获得单个转义符 (\
),您应该编写:\\
。要转义正则表达式内的转义,请将模式加倍:\\\\
。当然,这非常乏味,更糟糕的是,因为正则表达式有大量这样的转义序列。这就是为什么 Java 正则表达式还支持“引用”模式的垃圾部分,这允许您将模式编写为:
\\Q[]\\E
。编辑:正如另一个答案暗示的那样:
java.util.regex.Pattern.quote()
在\\Q
和\\E
之间执行此包装代码>.Regex patterns use
\
as escape character, but so does Java. So to get a single escape (\
) in a regex pattern you should write:\\
. To escape an escape inside a regex, double the pattern:\\\\
.Of course that's extremely tedious, made all the worse because regexes have a ton of escape sequences like that. Which is why Java regexes also support “quoting” litteral parts of the pattern and this allows you to write your pattern as:
\\Q[]\\E
.EDIT: As the other answer hints at:
java.util.regex.Pattern.quote()
performs this wrapping between\\Q
and\\E
.尝试 \\[ 和 \\]。您需要双重转义,因为 \ 也是字符串的转义字符(当您想在文本中使用双引号时, \" 也是如此)。因此,要在字符串中获得 \,您必须使用 \\。
Try \\[ and \\]. You need to double escape, because \ is also an escape character for strings (as is \" when you want to have double-quotes in your text). Therefore to get a \ in your string you have to use \\.
或者在更一般的情况下
or in the more general case