Java regex replaceAll multiline

JavaRegexReplaceall

Java Problem Overview


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

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.

Java Solutions


Solution 1 - Java

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")

or alternatively specify the flag in the pattern using (?s) e.g.

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

Solution 2 - Java

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

This would work

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

See https://stackoverflow.com/questions/3651725/match-multiline-text-using-regular-expression?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

Solution 3 - Java

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 any character including newline.

Code In Action

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobertView Question on Stackoverflow
Solution 1 - JavamikejView Answer on Stackoverflow
Solution 2 - JavatchristView Answer on Stackoverflow
Solution 3 - JavacodaddictView Answer on Stackoverflow