Adding square brackets to character class in Java regex

后端 未结 1 1043
北恋
北恋 2021-01-23 00:58

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

相关标签:
1条回答
  • 2021-01-23 01:38

    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("[^\\[({})\\]]","");
                              ^^     ^^
    
    0 讨论(0)
提交回复
热议问题