Java regex replaceAll multiline

前端 未结 3 785
被撕碎了的回忆
被撕碎了的回忆 2020-12-04 19:02

I have a problem with the replaceAll for a multiline string:

String regex = \"\\\\s*/\\\\*.*\\\\*/\";
String testWorks = \" /** this should be replaced **/ j         


        
相关标签:
3条回答
  • 2020-12-04 19:48

    Add Pattern.DOTALL to the compile, or (?s) to the pattern.

    This would work

    String regex = "(?s)\\s*/\\*.*\\*/";
    

    See Match multiline text using regular expression

    0 讨论(0)
  • 2020-12-04 19:55

    The meta character . matches any character other than newline. That is why your regex does not work for multi line case.

    To fix this replace . with [\d\D] that matches any character including newline.

    Code In Action

    0 讨论(0)
  • 2020-12-04 20:01

    You need to use the Pattern.DOTALL flag to say that the dot should match newlines. e.g.

    Pattern.compile(regex, Pattern.DOTALL).matcher(testIllegal).replaceAll("x")
    

    or alternatively specify the flag in the pattern using (?s) e.g.

    String regex = "(?s)\\s*/\\*.*\\*/";
    
    0 讨论(0)
提交回复
热议问题