DamDev
DamDev

Reputation: 125

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

Upvotes: 2

Views: 406

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

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

Upvotes: 2

Related Questions