Java正则表达式替换所有多行

Rob*_*ert 45 java regex replaceall

我对多行字符串的replaceAll有问题:

String regex = "\\s*/\\*.*\\*/";
String testWorks = " /** this should be replaced **/ just text";
String testIllegal = " /** this should be replaced \n **/ just text";

testWorks.replaceAll(regex, "x"); 
testIllegal.replaceAll(regex, "x"); 
Run Code Online (Sandbox Code Playgroud)

以上适用于testWorks,但不适用于testIllegal !? 为什么这样,我怎么能克服这个?我需要替换类似注释/*...*/的内容,它跨越多行.

mik*_*kej 74

您需要使用该Pattern.DOTALL标志来表示该点应与新行匹配.例如

Pattern.compile(regex, Pattern.DOTALL).matcher(testIllegal).replaceAll("x")
Run Code Online (Sandbox Code Playgroud)

或者使用(?s)例如在模式中指定标志

String regex = "(?s)\\s*/\\*.*\\*/";
Run Code Online (Sandbox Code Playgroud)


tch*_*ist 11

添加Pattern.DOTALL到编译或(?s)模式.

这会奏效

String regex = "(?s)\\s*/\\*.*\\*/";
Run Code Online (Sandbox Code Playgroud)

请参阅 使用正则表达式匹配多行文本


cod*_*ict 7

元字符.匹配除换行符之外的任何字符.这就是为什么你的正则表达式不适用于多行情况.

为了解决这个问题替换.[\d\D]匹配任何包括换行符.

代码在行动