Java正则表达式replaceAll多行 [英] Java regex replaceAll multiline
本文介绍了Java正则表达式replaceAll多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对多行字符串的replaceAll有问题:
I have a problem with the replaceAll for a multiline string:
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 !? 为什么会这样,我该如何克服呢?我需要替换诸如注释/* ... */跨越多行的内容.
The above works for testWorks, but not for testIllegal!? Why is that and how can I overcome this? I need to replace something like a comment /* ... */ that spans multiple lines.
推荐答案
您需要使用Pattern.DOTALL
标志说句点应与换行符匹配.例如
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")
或使用(?s)
例如在模式中指定标志
or alternatively specify the flag in the pattern using (?s)
e.g.
String regex = "(?s)\\s*/\\*.*\\*/";
这篇关于Java正则表达式replaceAll多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文