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

Combining Multiple Flags with Bitwise OR

Combine flags like CASE_INSENSITIVE | MULTILINE using bitwise OR to apply multiple behaviors at once.

Combining Multiple Flags with Bitwise OR

You'll learn how to apply multiple regular expression flags simultaneously using Java's bitwise OR operator.

Why Multiple Flags Matter

Sometimes you need several pattern behaviors at once—for example, case-insensitive matching and multiline mode together. Java provides a clean way to combine these compilation flags using the bitwise OR operator (|).

The Core Idea

When compiling a Pattern, you can pass multiple flags by joining them with |:

Pattern pattern = Pattern.compile(
    "^hello.*world$",
    Pattern.CASE_INSENSITIVE | Pattern.MULTILINE
);

This tells Java: "Apply both case-insensitive matching and multiline anchors."

How It Works

Each flag is represented internally as a distinct bit in an integer. The bitwise OR operation combines these bits without conflict:

  • CASE_INSENSITIVE might be bit 2
  • MULTILINE might be bit 8
  • DOTALL might be bit 32

When you OR them together (flag1 | flag2 | flag3), you create a single integer where all relevant bits are set, enabling all behaviors simultaneously.

Practical Example

// Match "java" at line starts, case-insensitively, with . matching newlines
Pattern p = Pattern.compile(
    "^java.*code",
    Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL
);

This pattern will:

  • Match "JAVA", "Java", or "java" (case-insensitive)
  • Treat ^ as matching after any newline (multiline)
  • Allow .* to span across line breaks (dotall)

Key Takeaway: Use the bitwise OR operator (|) to combine multiple Pattern flags like CASE_INSENSITIVE | MULTILINE | DOTALL, enabling several regex behaviors in a single compiled pattern.