51

我对多行字符串的 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"); 

以上适用于 testWorks,但不适用于 testIllegal!?为什么会这样,我该如何克服?我需要替换跨越多行的注释 /* ... */ 之类的内容。

4

3 回答 3

89

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

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

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

String regex = "(?s)\\s*/\\*.*\\*/";
于 2010-11-11T12:17:21.653 回答
14

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

这会起作用

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

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

于 2010-11-11T12:17:37.123 回答
7

元字符.匹配除换行符以外的任何字符。这就是为什么您的正则表达式不适用于多行案例的原因。

.[\d\D]匹配任何字符(包括换行符)来修复此替换。

代码在行动

于 2010-11-11T12:17:02.913 回答