Java正则表达式replaceAll多行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4154239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java regex replaceAll multiline
提问by Robert
I have a problem with the replaceAll for a multiline string:
我对多行字符串的 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");
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.
以上适用于 testWorks,但不适用于 testIllegal!?为什么会这样,我该如何克服?我需要替换像注释 /* ... */ 这样跨越多行的内容。
采纳答案by mikej
You need to use the Pattern.DOTALL
flag to say that the dot should match newlines. e.g.
您需要使用Pattern.DOTALL
标志来说明点应与换行符匹配。例如
Pattern.compile(regex, Pattern.DOTALL).matcher(testIllegal).replaceAll("x")
or alternatively specify the flag in the pattern using (?s)
e.g.
或者使用(?s)
例如在模式中指定标志
String regex = "(?s)\s*/\*.*\*/";
回答by codaddict
The meta character .
matches any character other than newline. That is why your regex does not work for multi line case.
元字符.
匹配除换行符以外的任何字符。这就是为什么您的正则表达式不适用于多行情况。
To fix this replace .
with [\d\D]
that matches anycharacter including newline.
要修复此替换.
为[\d\D]
匹配任何字符(包括换行符)。
回答by tchrist
Add Pattern.DOTALL
to the compile, or (?s)
to the pattern.
添加Pattern.DOTALL
到编译或(?s)
模式中。
This would work
这会工作
String regex = "(?s)\s*/\*.*\*/";
See Match multiline text using regular expression
请参见 使用正则表达式匹配多行文本