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:
- Using CASE_INSENSITIVE flag
- 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()); } } } |
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()); } } } |
GFG gfg