July 12 2016

Java regex case insensitive

Java regex case insensitive

By default Java Regex matching is case sensitive. To make your search case-insensitive, pass ‘Pattern.CASE_INSENSITIVE’ (2) flag to compile method.

Pattern pattern2 = Pattern.compile(“apple”, Pattern.CASE_INSENSITIVE);


package test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JavaRegexCaseInsensitive {

public static void main(String[] args) {

// Java regex case insensitive

String message = "Apple a day keeps the doctor away";

System.out.println("Case sensitive");

Pattern pattern1 = Pattern.compile("apple");

Matcher matcher1 = pattern1.matcher(message);

if (matcher1.find()) {
} else {
System.out.println("Not Found");

System.out.println("Case insensitive");

Pattern pattern2 = Pattern.compile("apple", Pattern.CASE_INSENSITIVE);

Matcher matcher2 = pattern2.matcher(message);

if (matcher2.find()) {
} else {
System.out.println("Not Found");


Case sensitive
Not Found
Case insensitive

Copyright © 2014. All rights reserved.

Posted July 12, 2016 by answersz in category Core Java

Leave a Comment

Your email address will not be published. Required fields are marked *