Course contentsShow
← Java
Lesson 2316 of 2,87044. Regular ExpressionsFree lesson

DOTALL Flag: Making . Match Newlines

Use Pattern.DOTALL to make the dot metacharacter match any character including newlines.

DOTALL Flag: Making . Match Newlines

You'll learn how to make the dot metacharacter match newline characters by enabling the DOTALL flag.

The Problem with the Default Dot

By default, the dot (.) metacharacter matches any character except line terminators like \n. This limitation can be frustrating when you want to match patterns that span multiple lines. For example, if you're trying to match content between HTML tags that may contain newlines, the default dot won't work as expected.

Enabling DOTALL Mode

The Pattern.DOTALL flag (also called "single-line mode" in some regex flavors) changes this behavior, making the dot match any character including newlines. You can enable it when compiling your pattern:

Pattern pattern = Pattern.compile("start.*end", Pattern.DOTALL);

Now . will happily match across line breaks.

Inline Flag Syntax

Just like with other flags, you can embed DOTALL mode directly in your pattern using (?s):

Pattern pattern = Pattern.compile("(?s)start.*end");

The s stands for "single-line" (meaning the entire input is treated as one continuous line for the dot's purposes).

Example: Matching Multi-Line Content

String text = "start\nSome content\nhere\nend";

// Without DOTALL - no match
Pattern withoutFlag = Pattern.compile("start.*end");
System.out.println(withoutFlag.matcher(text).find()); // false

// With DOTALL - matches across newlines
Pattern withFlag = Pattern.compile("start.*end", Pattern.DOTALL);
System.out.println(withFlag.matcher(text).find()); // true

Key Takeaway: Use Pattern.DOTALL or the inline (?s) flag to make the dot metacharacter match newline characters, enabling patterns to span multiple lines seamlessly.