在Java正则表达式中向字符类添加方括号 [英] Adding square brackets to character class in Java regex
问题描述
我想逐行从文件lne读取内容String
,并在每一行中删除不是以下[ { } ]
之一的所有caharcters
我想使用一种方法:
I would like to read a content String
from file lne by line, and in each line remove all caharcters that are not one of the following [ { } ]
I wanted to used a method:
line = line.replaceAll("[^[({})]]","");
,但问题是char [
和]
在正则表达式语法中意味着其他含义.
如何处理?
but the problem is that char [
and ]
means in regex syntax something else.
How to deal with it?
最诚挚的问候
推荐答案
在Java中,正则表达式字符类可以具有并集和交集,因此,如果要对[
和]
进行转义,则必须在它们内部进行转义.作为文字符号.并且由于\
可用于定义转义序列,因此应将其加倍以表示文字正则表达式转义的\
.
In Java, the regex character classes can have unions and intersections, thus, [
and ]
must be escaped inside if you want them to be treated as literal symbols. And since \
can be used to define escape sequences, it should be doubled to denote a literal regex-escaping \
.
使用
line = line.replaceAll("[^\\[({})\\]]","");
^^ ^^
这篇关于在Java正则表达式中向字符类添加方括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!