How to use regular expression in Java to pattern match?

JavaServer Side ProgrammingProgramming

A regular expression is a string of characters that defines/forms a pattern to search an input text. A regular expression may contain one or more characters, using a regular expression you can search or replace a string.

Java provides the java.util.regex package for pattern matching with regular expressions. The pattern class of this package is a compiled representation of a regular expression. To match a regular expression with a String this class provides two methods namely −

  • compile(): This method accepts a String representing a regular expression and returns an object of the Pattern object.
  • matcher(): This method accepts a String value and creates a matcher object which matches the given String to the pattern represented by the current pattern object.


Following Java program accepts a string from the user, verifies whether it contains alphabet (both cases), It also accepts digits.

Live Demo

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
   public static void main( String args[] ) {
      String regex = "[a-zA-Z][0-9]?";
      Scanner sc = new Scanner(;
      System.out.println("Enter an input string: ");
      String input = sc.nextLine();
      //Creating a Pattern object
      Pattern p = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher m = p.matcher(input);  
      if(m.find()) {
         System.out.println("Match occurred");
      }else {
         System.out.println("Match not occurred");

Output 1

Enter an input string:
sample text
Match occurred

Output 2

Enter an input string:
sample text 34 56
Match occurred
Published on 05-Feb-2021 10:26:33