Adding square brackets to character class in Java regex

做~自己de王妃 提交于 2019-12-02 04:55:56

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/34912455/adding-square-brackets-to-character-class-in-java-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!