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:
- 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
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class GFG {
public static void main(String[] args)
{
String str = "From GFG class. Welcome to gfg." ;
Pattern patrn = Pattern.compile(
"gfg" , Pattern.CASE_INSENSITIVE);
Matcher match = patrn.matcher(str);
while (match.find()) {
System.out.println(match.group());
}
}
}
|
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
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class GFG {
public static void main(String[] args)
{
String str = "From GFG class. Welcome to gfg." ;
Pattern patrn = Pattern.compile( "(?i)gfg" );
Matcher match = patrn.matcher(str);
while (match.find()) {
System.out.println(match.group());
}
}
}
|
Share your thoughts in the comments
Please Login to comment...