How to select any character across multiple lines in Java

You can do that using the following pattern in the compile static method of the java.util.regex.Pattern class. The pattern is (.|n|r)*? which means: any character (the .) or (the |) n or r. Zero or more times (the *) of the whole stuff.

Example: The following method strips the multiline comments (those between /* and */) from a string passed in and returns the resulting string:

import java.util.regex;

// ... other code 

// Strip multiline comments
public void deleteMultilineComments(String subject) {
  Pattern pattern = Pattern.compile("(/\\*(.|n|r)*?\\*/)");
  Matcher matcher = pattern.matcher(subject);
  return matcher.replaceAll("");

Note: rn works for Windows systems. n works for Unix-like systems. r works for Mac systems.

comments powered by Disqus