Java - 在正则表达式中转义元字符[和] [英] Java - Escaping Meta-characters [ and ] in Regex
问题描述
我试图用另一个字符串替换第一个字符串[]:
I am attempting to replace the first occurrence of the string "[]" in another string:
aString.replaceFirst([],blah) ;
aString.replaceFirst("[]", "blah");
我收到错误:
java.util.regex.PatternSyntaxException:索引1附近的未关闭的字符类[]
I get the error: java.util.regex.PatternSyntaxException: Unclosed character class near index 1 []
[和]显然是元字符,但是当我尝试用\ $ b $ e eclipse来逃避它们时,eclipse抱怨说它不是一个有效的转义序列。
[ 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?
谢谢
推荐答案
正则表达式模式使用 \
作为转义字符,但Java也是如此。因此,要以正则表达式模式获取单个转义( \
),您应该写: \\
。要逃避正则表达式中的转义,将模式加倍: \\\\\
。
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: \\\\
.
当然这是非常繁琐的,更糟糕的是,因为正则表达式有这么多的转义序列。这就是为什么Java正则表达式还支持引用模式的混合部分,这样可以将模式写成: \\\QQ [] \\E
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.util.regex.Pattern.quote()
执行这个包裹在 \\Q
和 \\E
之间。
As the other answer hints at: java.util.regex.Pattern.quote()
performs this wrapping between \\Q
and \\E
.
这篇关于Java - 在正则表达式中转义元字符[和]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!