How match a string irrespective of case using Java regex.



The compile method of the patter class accepts two parameters −

  • A string value representing the regular expression.
  • An integer value a field of the Pattern class.

This CASE_INSENSITIVE field of the Pattern class matches characters irrespective of case. Therefore, if you pass as flag value to the compile() method along with your regular expression, characters of both cases will be matched.

Example 1

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();       //Regular expression to find the required character       String regex = "test";       //Compiling the regular expression       Pattern pattern = Pattern.compile(regex);//, Pattern.CASE_INSENSITIVE);       //Retrieving the matcher object       Matcher matcher = pattern.matcher(input);       int count =0;       while (matcher.find()) {          count++;       }       System.out.println("Number of occurrences: "+count);    } }

Output

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

Example 2

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("Given string is a boolean type");       } else {          System.out.println("Given string is not a boolean type");       }    } }

Output

Enter a string value: TRUE Given string is a boolean type
Updated on: 2019-11-21T08:06:13+05:30

258 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements