MULTILINE Flag: ^ and $ Behavior
What you'll learn: How the MULTILINE flag transforms ^ and $ from string-boundary anchors into line-boundary anchors.
The Default Behavior
By default, the ^ and $ anchors in Java regular expressions match only at the very beginning and end of the entire input string. If your string contains multiple lines (separated by newline characters), ^ won't match at the start of each line—only at the start of the whole string. Similarly, $ matches only at the very end.
What MULTILINE Changes
When you enable the MULTILINE flag using Pattern.MULTILINE, the behavior shifts:
^now matches at the start of each line (right after any line terminator)$now matches at the end of each line (right before any line terminator)
Think of it like switching from "document mode" to "line-by-line mode." Without MULTILINE, your anchors see the entire string as one unit. With MULTILINE, they treat each line as its own matchable boundary.
Practical Example
String text = "apple\nbanana\napricot";
// Without MULTILINE: matches only lines starting with 'a' if entire string starts with 'a'
Pattern withoutFlag = Pattern.compile("^a.*");
Matcher m1 = withoutFlag.matcher(text);
System.out.println(m1.find()); // true (matches "apple" at string start)
// With MULTILINE: matches each line starting with 'a'
Pattern withFlag = Pattern.compile("^a.*", Pattern.MULTILINE);
Matcher m2 = withFlag.matcher(text);
while (m2.find()) {
System.out.println(m2.group()); // "apple", then "apricot"
}
The MULTILINE flag is essential when processing multi-line text where you need to validate or extract content at the beginning or end of individual lines, not just the entire string.
Key Takeaway: The MULTILINE flag makes ^ and $ match at line boundaries instead of only string boundaries, enabling line-by-line pattern matching in multi-line text.