In this article, we are able to discover ways to make Java Regular Expression case-insensitive in Java. Java Regular Expression is used to find, match, and extract facts from man or woman sequences. Java Regular Expressions are case-touchy through default. But with the assist of Regular Expression, we are able to make the Java Regular Expression case-insensitive. There are approaches to make Regular Expression case-insensitive:
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 byskip the sample at the side of 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