Thursday, September 4, 2025
HomeLanguagesJavaHow to Make Java Regular Expression Case Insensitive in Java?

How to Make Java Regular Expression Case Insensitive in Java?

In this article, we will learn how to make Java Regular Expression case-insensitive in Java. Java Regular Expression is used to find, match, and extract data from character sequences. Java Regular Expressions are case-sensitive by default. But with the help of Regular Expression, we can make the Java Regular Expression case-insensitive. There are two ways to make Regular Expression case-insensitive:

  1. Using CASE_INSENSITIVE flag
  2. Using modifier

1. Using CASE_INSENSITIVE flag: The compile method of the Pattern class takes the CASE_INSENSITIVE flag along with the pattern to make the Expression case-insensitive. Below is the implementation:

Java




// Java program demonstrate How to make Java
// Regular Expression case insensitive in Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
class GFG {
    public static void main(String[] args)
    {
  
        // String
        String str = "From GFG class. Welcome to gfg.";
  
        // Create pattern to match along
        // with the flag CASE_INSENSITIVE
        Pattern patrn = Pattern.compile(
            "gfg", Pattern.CASE_INSENSITIVE);
  
        // All metched patrn from str case
        // insensitive or case sensitive
        Matcher match = patrn.matcher(str);
  
        while (match.find()) {
            // Print matched Patterns
            System.out.println(match.group());
        }
    }
}


Output

GFG
gfg

2. Using modifier: The ” ?i “ modifier used to make a Java Regular Expression case-insensitive. So to make the Java Regular Expression case-insensitive we pass the pattern along with the ” ?i ” modifier that makes it case-insensitive. Below is the implementation:

Java




// Java program demonstrate How to make Java
// Regular Expression case insensitive in Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
class GFG {
    public static void main(String[] args)
    {
  
        // String
        String str = "From GFG class. Welcome to gfg.";
  
        // Create pattern to match along
        // with the ?i modifier
        Pattern patrn = Pattern.compile("(?i)gfg");
  
        // All metched patrn from str case
        // insensitive or case sensitive
        Matcher match = patrn.matcher(str);
  
        while (match.find()) {
            // Print matched Patterns
            System.out.println(match.group());
        }
    }
}


Output

GFG
gfg
RELATED ARTICLES

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6628 POSTS0 COMMENTS
Nicole Veronica
11799 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11858 POSTS0 COMMENTS
Shaida Kate Naidoo
6749 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6698 POSTS0 COMMENTS
Umr Jansen
6716 POSTS0 COMMENTS