Skip to content
Related Articles

Related Articles

How to Make Java Regular Expression Case Insensitive in Java?
  • Last Updated : 09 Mar, 2021

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

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :