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

How to use Java regular expressions to match characters in a given string (including case)?

Java's java.util.regex package provides various classes to find specific patterns in character sequences. The pattern class in this package is the compiled representation of regular expressions.

To match specific characters in the given input string-

  • to obtain the input string.

  • of this kindcompile()method accepts a string value representing the regular expression and an integer value representing the flags to return a Pattern object. Bypass compiling the regular expression-

    • Pattern matcher" [] "with the required characters, such as: "[t]".

    • flag CASE_INSENSITIVE to ignore case.

  • Patternthe classmatcher()method accepts an input string and returns a Matcher object. Use this method to create/retrieve matcher object.

  • find() -Use the Matcher'sfind()method to perform matching.

Example

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CompileExample {
   public static void main(String args[]) {
      //Read string value
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string");
      String input = sc.nextLine();
      //Regular expression to find numbers
      String regex = "[t]";
      //Compile regular expression
      Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
      //Retrieve matcher object
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count++;
      }
      System.out.println("Number of matches:");+count);
   }
}

Output result

Enter input string
w3codebox
Number of matches: 3