Java 正则表达式 replaceAll 多行

标签 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"); 

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

最佳答案

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

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

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

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

关于Java 正则表达式 replaceAll 多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4154239/

相关文章:

c++ - 在 C++ 中使用 regex/boost 查找两个数字之间的数字

javascript - 正则表达式/_/g 是什么意思?

java - 在 JSP NetBeans 中报告语法错误但结果看起来并且工作正常

java - 来自 Java 的 White Report 和 jasper 报告

python - 如何使用Python替换字符串中的数值?

Java 全部替换,每出现两次就替换一次

java - 如何更改java中标签之间的内容?

java - 深入理解Java中的Reactive Programming

java - 如何在某一列上使用 Hibernate 搜索返回列表?

JavaScript replaceAll 不区分大小写的搜索使用变量而不是字符串