简体   繁体   中英

Adding square brackets to character class in Java regex

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("[^[({})]]","");

but the problem is that char [ and ] means in regex syntax something else. How to deal with it?

Best regards

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

Use

line = line.replaceAll("[^\\[({})\\]]","");
                          ^^     ^^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM