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

Inline Flag Syntax: (?m) for Multiline Mode

Embed multiline mode in patterns using (?m), enabling line-by-line matching within a single string.

Inline Flag Syntax: (?m) for Multiline Mode

What you'll learn: How to embed multiline mode directly into your regex pattern using (?m), allowing ^ and $ to match line boundaries within a string.

Why Inline Flags Matter

In the previous lesson, you learned about the MULTILINE flag passed during pattern compilation. But what if you want to enable multiline mode within the pattern itself, without touching the compilation code? That's where inline flag syntax comes in.

The (?m) Syntax

By placing (?m) at the beginning of your regex pattern, you activate multiline mode for that pattern. This means:

  • ^ matches the start of any line (not just the entire string)
  • $ matches the end of any line (not just the entire string)

Think of it like this: (?m) is a switch you flip inside the pattern itself, making it self-contained and portable.

Example in Plain Terms

Imagine you have a multi-line string like:

"apple\nbanana\ncherry"

Without multiline mode, ^banana wouldn't match because "banana" isn't at the string's start. But with (?m)^banana, it matches because ^ now means "start of a line," and "banana" is at the start of the second line.

When to Use Inline Syntax

Use (?m) when:

  • You want the pattern itself to be self-documenting
  • You're passing patterns as strings and can't control compilation flags
  • You need different flags for different parts of complex patterns

You can even turn it off later in the pattern with (?-m) if needed.

Key Takeaway:
The (?m) inline flag embeds multiline mode directly into your regex pattern, making ^ and $ match line boundaries rather than string boundaries, without requiring flags during compilation.