How to Make Java Regular Expression Case Insensitive in Java?

In Java, regular expressions (regex) are powerful tools for pattern matching within strings. By default, Java's regex engine is case sensitive, meaning it distinguishes between uppercase and lowercase letters in patterns and input strings. However, there are methods and techniques to make Java regular expressions case insensitive when needed.

  1. Using CASE_INSENSITIVE flag
  2. Case Insensitivity with Complex Pattern
  3. Case Insensitivity with Groups
  4. Using Modifier

1. Using CASE_INSENSITIVE flag

Java provides a straightforward way to make regular expressions case insensitive by using the Pattern.CASE_INSENSITIVE flag with the compile method of the Pattern class. This flag allows the regex engine to ignore differences in letter case when matching patterns against input strings.

File Name: RegexExample.java

Output:

 
Match found!   

Case Insensitivity with Complex Pattern

File Name: RegexExample2.java

Output:

 
Match found at index: 0
Match found at index: 12
Match found at index: 29   

Case Insensitivity with Groups

To use case insensitivity with regular expression groups in Java, we apply the same CASE_INSENSITIVE flag but include groups in pattern. Here's an example:

File Name: CaseInsensitiveGroupsExample.java

Output:

 
Full match: name: John (email: [email protected])
Name group: name: John
Name: John
Email group: [email protected]

Full match: name: alice (email: [email protected])
Name group: name: alice
Name: alice
Email group: [email protected]   

2. Using Modifier

Alternatively, we can embed the (?i) modifier directly within the regex pattern itself. It applies case insensitivity locally to the part of the pattern where it is used.

File Name: UsingModifier.java

Output:

 
Match found!