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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:06:32  来源:igfitidea点击:

Java regex replaceAll multiline

javaregexreplaceall

提问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.DOTALLflag 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]匹配任何字符(包括换行符)。

Code In Action

代码在行动

回答by tchrist

Add Pattern.DOTALLto the compile, or (?s)to the pattern.

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

This would work

这会工作

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

See Match multiline text using regular expression

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