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

Inline Flags: Combining (?im) and Scoping

Use multiple inline flags together and understand how to scope flag effects within parts of a pattern.

Inline Flags: Combining (?im) and Scoping

You'll learn how to use multiple inline flags together and control exactly where those flags apply within your regex pattern.

Combining Multiple Inline Flags

Just as you can use (?i) for case-insensitivity or (?m) for multiline mode separately, you can combine multiple flags in a single inline group. Simply list the flag letters together:

Pattern pattern = Pattern.compile("(?im)^hello.*world$");

This pattern is both case-insensitive (i) and multiline (m), so ^ and $ match line boundaries, and letter casing is ignored.

You can also include s for DOTALL mode: (?ims) would enable all three flags inline.

Scoping: Applying Flags to Part of a Pattern

The real power comes from scoping flags to specific parts of your pattern. Use parentheses to limit where flags apply:

Pattern pattern = Pattern.compile("(?i:hello) WORLD");

Here, only hello is case-insensitive—it matches "Hello", "HELLO", "hElLo", etc. But WORLD must be uppercase because the (?i:...) scope ends after the closing parenthesis.

Think of it like a spotlight: The flags shine only on the text within the parentheses, leaving the rest of the pattern unaffected.

Practical Example

String text = "Error: timeout";
Pattern pattern = Pattern.compile("(?i:error|warning): \\w+");
Matcher matcher = pattern.matcher(text);

if (matcher.find()) {
    System.out.println("Found: " + matcher.group()); // "Error: timeout"
}

The keywords "error" and "warning" are case-insensitive, but the rest of the pattern follows normal rules.

Key Takeaway: Combine inline flags like (?im) to enable multiple modes at once, and use scoped syntax (?flags:pattern) to apply flags only to specific parts of your regex, giving you surgical control over pattern behavior.