The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.util.regex  [26 examples] > Lines  [6 examples]

e444. 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

 Related Examples
e441. Using a Regular Expression to Filter Lines from a Reader
e442. Implementing a FilterReader to Filter Lines Based on a Regular Expression
e443. Matching Line Boundaries in a Regular Expression
e445. Reading Lines from a String Using a Regular Expression
e446. Removing Line Termination Characters from a String

See also: Flags    Groups    Paragraphs    Searching and Replacing    Tokenizing   


© 2002 Addison-Wesley.