Inline Flag Syntax: (?i) for Case Insensitivity
You'll learn how to embed case-insensitive mode directly into your regex patterns and control exactly which parts ignore case.
Why Inline Flags?
You've already seen the CASE_INSENSITIVE flag when compiling patterns. But what if you only want part of your pattern to be case-insensitive? Inline flag syntax lets you embed the flag directly in the pattern string itself, giving you surgical control over which sections ignore case.
The (?i) Syntax
The inline flag (?i) turns on case-insensitive matching from that point forward in the pattern:
Pattern pattern = Pattern.compile("hello(?i)world");
Matcher matcher = pattern.matcher("helloWORLD");
System.out.println(matcher.matches()); // true
// "hello" must match exactly, but "world" ignores case
Here, "hello" must match in lowercase, but "world" can be any mix of upper and lowercase.
Scoped Inline Flags
You can limit the case-insensitive portion using a non-capturing group:
Pattern pattern = Pattern.compile("(?i:abc)def");
Matcher matcher1 = pattern.matcher("ABCdef");
System.out.println(matcher1.matches()); // true
Matcher matcher2 = pattern.matcher("ABCDEF");
System.out.println(matcher2.matches()); // false
// Only "abc" ignores case; "def" must be lowercase
The syntax (?i:...) applies case-insensitivity only within that group.
Think of It Like a Light Switch
Imagine (?i) as flipping a light switch: everything after it is illuminated (case-insensitive). Using (?i:...) is like shining a flashlight on just one spot—only what's inside the group is affected.
Turning Off the Flag
Use (?-i) to turn case sensitivity back on:
Pattern pattern = Pattern.compile("(?i)hello(?-i)world");
// "hello" ignores case, "world" must match exactly
Key Takeaway:
Use (?i) to enable case-insensitive matching inline, (?i:...) to scope it to specific groups, and (?-i) to turn it back off—giving you precise control over which parts of your pattern ignore case.