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