English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

How to match strings with Java regex regardless of case.

The compile method of the Pattern class accepts two parameters-

  • Represents the string value of the regular expression.

  • An integer value, a field of the Pattern class.

The CASE_INSENSITIVE field of the Pattern class matches characters regardless of case. Therefore, if the flag valuecompile()Both cases of characters will match if passed to the method along with the regular expression.

Example1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input data: ");
      String input = sc.nextLine();
      //The regular expression is used to find the required characters
      String regex = "test";
      //Compile the regular expression
      Pattern pattern = Pattern.compile(regex);//, Pattern.CASE_INSENSITIVE);
      //Search for the matching object
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while (matcher.find()) {
         count++;
      
      System.out.println("Number of occurrences: ");+count);
   

Output Result

Enter input data:
test TEST Test sample data
Number of occurrences: 3

Example2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class VerifyBoolean {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a string value: ");
      String str = sc.next();
      Pattern pattern = Pattern.compile("true|false", Pattern.CASE_INSENSITIVE);
      Matcher matcher = pattern.matcher(str);
      if(matcher.matches()){
         System.out.println("The given string is a boolean type");
      } else {
         System.out.println("The given string is not a boolean type");
      
   

Output Result

Enter a string value:
TRUE
The given string is of boolean type