Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex replaceAll multiline

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.

like image 838
Robert Avatar asked Nov 11 '10 12:11

Robert


People also ask

How do you replace multiple lines in Java?

Click Ctrl + F and select "Regular Expression" and then search the lines. In case to perform the same on multiple files, click Ctrl + H, click on 'File Search' and perform the same. Save this answer.

What is pattern multiline Java?

Pattern. MULTILINE or (? m) tells Java to accept the anchors ^ and $ to match at the start and end of each line (otherwise they only match at the start/end of the entire string).


1 Answers

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*/\\*.*\\*/"; 
like image 148
mikej Avatar answered Sep 23 '22 17:09

mikej