Java - 在正则表达式中转义元字符 [ 和 ]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7904695/
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 21:55:20  来源:igfitidea点击:

Java - Escaping Meta-characters [ and ] in Regex

javaregexescaping

提问by ZirconCode

I am attempting to replace the first occurrence of the string "[]" in another string:

我试图替换另一个字符串中第一次出现的字符串“[]”:

aString.replaceFirst("[]", "blah");

aString.replaceFirst("[]", "等等");

I get the error: java.util.regex.PatternSyntaxException: Unclosed character class near index 1 []

我收到错误消息:java.util.regex.PatternSyntaxException:索引 1 附近未关闭的字符类 []

[ and ] are obviously metacharacters, however when I try to escape them with a \ eclipse complains that it is not a valid escape sequence.

[ 和 ] 显然是元字符,但是当我尝试用 \ eclipse 转义它们时,它会抱怨它不是有效的转义序列。

I've looked but couldn't find, what am I missing?

我找过但找不到,我错过了什么?

Thank You

谢谢

回答by user268396

Regex patterns use \as escape character, but so does Java. So to get a singleescape (\) in a regex pattern you should write: \\. To escape an escape inside a regex, double the pattern: \\\\.

正则表达式模式\用作转义字符,但 Java 也是如此。因此,要在正则表达式模式中获得单个转义符 ( \),您应该这样写:\\. 要在正则表达式中转义,请将模式加倍:\\\\.

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.

当然,这非常乏味,而且更糟,因为正则表达式有大量这样的转义序列。这就是为什么 Java 正则表达式还支持“引用”模式的文字部分,这允许您将模式编写为:\\Q[]\\E.

EDIT: As the other answer hints at: java.util.regex.Pattern.quote()performs this wrapping between \\Qand \\E.

编辑:正如另一个答案所暗示的:java.util.regex.Pattern.quote()\\Q和之间执行这种包装\\E

回答by pushy

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 \\.

试试 \\[ 和 \\]。您需要双重转义,因为 \ 也是字符串的转义字符(当您想在文本中使用双引号时,就像 \" 一样)。因此,要在字符串中获得 \,您必须使用 \\。

回答by ratchet freak

aString.replaceFirst("\[\]", "blah");

or in the more general case

或者在更一般的情况下

aString.replaceFirst(java.util.regex.Pattern.quote("[]"), "blah");