Matching Across Line Boundaries in a Regular Expression

By default, the any-character matcher (.) does not match line termination characters such as \n and \r. To allow dot (.) to match line termination characters, the pattern should be compiled with the dotall flag enabled.

It is also possible to enable dotall mode within a pattern using the inline modifier (?s). For example, dotall mode is enabled in the pattern (?s)a.*b. Dotall mode can be disabled using (?-s).

CharSequence inputStr = "abc\ndef"; String patternStr = ".*c.+d.*"; // Compile with dotall enabled Pattern pattern = Pattern.compile(patternStr, Pattern.DOTALL); Matcher matcher = pattern.matcher(inputStr); boolean matchFound = matcher.matches(); // true // Use an inline modifier to enable dotall mode matchFound = pattern.matches(".*c.+d.*", "abc\r\ndef"); // false matchFound = pattern.matches("(?s).*c.+d.*", "abc\r\ndef"); // true

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.