在Java正则表达式中的字符类中使用方括号 [英] Using square brackets inside character class in Java regex

查看:92
本文介绍了在Java正则表达式中的字符类中使用方括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我为替换字符串中的特殊字符&!)(}{][^"~*?:;\+-而编写的正则表达式,但是以某种方式无法替换[& ],因为它充当正则表达式的开始和结束.我该怎么办?

Below is the regex I have written to replace the special chars &!)(}{][^"~*?:;\+- from a string, but somehow it is not able to replace [ & ] from it as it acts as beginning and closing of regex. How can I do that?

System.out.println(" &!)(}{][^\"~*?:;\\+-".replaceAll("[| |&|!|)|(|}|{|^|\"|~|*|?|:|;|\\\\|+|-]", "_"));
}

现在的输出:_______][__________

推荐答案

您只需要在Java正则表达式的字符类中转义[]即可.

You just need to escape the [ and ] inside a character class in a Java regex.

此外,您无需在字符类中将|作为替换符号,因为它被视为文字|.

Also, you do not need to put | as alternation symbol in the character class as it is treated as a literal |.

System.out.println(" &!)(}{][^\"~*?:;\\+-".replaceAll("[\\]\\[ &!)(}{^\"~*?:;\\\\+-]", "_"));
// => ___________________

请参见 Java演示

&dagger ;: 请注意,在PCRE/Python/.NET,POSIX中,如果将方括号放在正确的位置,则不必在字符类中转义方括号:[]ab[].在JavaScript中,您始终必须转义]:/[^\]abc[]/.在Java和ICU正则表达式中,必须始终在字符类内同时转义[]. – WiktorStribiżew17年1月10日在12:39

†: Note that in PCRE/Python/.NET, POSIX, you do not have to escape square brackets in the character class if you put them at the right places: []ab[]. In JavaScript, you always have to escape ]: /[^\]abc[]/. In Java and ICU regexps, you must always escape both [ and ] inside the character class. – Wiktor Stribiżew Jan 10 '17 at 12:39

这篇关于在Java正则表达式中的字符类中使用方括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆