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

The Dot Metacharacter and DOTALL Mode

Understand how dot matches any character except line terminators, and how Pattern.DOTALL changes this behavior.

The Dot Metacharacter and DOTALL Mode

You'll learn how the dot (.) wildcard behaves with line terminators and how to override that behavior when needed.

What the Dot Actually Matches

In regular expressions, the dot metacharacter (.) is often described as "match any character," but there's a crucial exception: by default, dot does NOT match line terminators like \n (newline) or \r (carriage return).

Think of the dot as a cautious wildcard—it matches letters, digits, punctuation, spaces, even tabs, but it stops at line boundaries. This prevents patterns from accidentally spanning multiple lines when you're processing line-by-line text.

Pattern pattern = Pattern.compile("a.c");
Matcher matcher = pattern.matcher("abc");
System.out.println(matcher.matches()); // true - dot matches 'b'

matcher = pattern.matcher("a\nc");
System.out.println(matcher.matches()); // false - dot doesn't match '\n'

Enabling DOTALL Mode

When you do need the dot to match line terminators, use the Pattern.DOTALL flag (also called "single-line mode" in some regex flavors):

Pattern pattern = Pattern.compile("a.c", Pattern.DOTALL);
Matcher matcher = pattern.matcher("a\nc");
System.out.println(matcher.matches()); // true - now dot matches '\n'

With DOTALL, the dot becomes a true "match anything" wildcard. This is useful when extracting content that spans multiple lines or when line boundaries are irrelevant to your pattern.

Analogy: Default dot mode is like a reader who stops at every paragraph break. DOTALL mode is like a reader who ignores those breaks and reads straight through.

Key Takeaway: The dot (.) matches any character except line terminators by default; enable Pattern.DOTALL to make dot match truly everything, including newlines.