Compiling with Flags
What You'll Learn
You'll learn how to modify regex matching behavior by passing flags like Pattern.CASE_INSENSITIVE to Pattern.compile().
The Core Idea
Until now, you've compiled patterns using Pattern.compile("regex"), which uses default matching rules. But sometimes you need different behavior—like ignoring case, matching across multiple lines, or enabling comments in your regex. Java provides flags (also called "match options") that you pass as a second argument to Pattern.compile() to customize how the pattern engine interprets your regex.
Think of flags like settings on a camera: the basic camera works fine, but adjusting ISO, aperture, or shutter speed gives you control over how the image is captured. Similarly, flags give you control over how patterns are matched.
Common Flags
// Case-insensitive matching
Pattern pattern = Pattern.compile("hello", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("HELLO World");
matcher.matches(); // true — case doesn't matter
// Multiline mode: ^ and $ match line boundaries
Pattern multiline = Pattern.compile("^start", Pattern.MULTILINE);
// Dotall mode: . matches newlines too
Pattern dotall = Pattern.compile(".*", Pattern.DOTALL);
// Combine flags with bitwise OR
Pattern combined = Pattern.compile("test",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
The most commonly used flag is Pattern.CASE_INSENSITIVE, which makes your pattern ignore upper/lower case distinctions—perfect for user input validation where "Yes", "YES", and "yes" should all match.
You combine multiple flags using the bitwise OR operator (|), allowing you to stack behaviors like case-insensitivity plus multiline mode.
Key Takeaway
Pass flags as a second argument to Pattern.compile() to customize regex matching behavior, with Pattern.CASE_INSENSITIVE being the most common for ignoring case distinctions—combine multiple flags using the | operator.