Is Java matcher thread safe in Java?

JavaServer Side ProgrammingProgramming

A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. They can be used to search, edit, or manipulate text and data. Java provides the java.util.regex package for pattern matching with regular expressions.

Matcher class

A Matcher object is the engine that interprets the pattern and performs match operations against an input string. Like the Pattern class, Matcher defines no public constructors. You obtain a Matcher object by invoking the matcher() method on a Pattern object.

The Instances of this class are not safe for use by multiple concurrent threads.

Example

Following Java program accepts 5 strings from the user and prints the strings starting with a digit.

Live Demo

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StartingwithDigit {
   public static void main( String args[] ) {
      String regex = "^[0-9].*$";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter 5 input strings: ");
      String input[] = new String[5];
      for (int i=0; i<5; i++) {
         input[i] = sc.nextLine();
      }
      //Creating a Pattern object
      Pattern p = Pattern.compile(regex);
      System.out.println("Strings starting with digits: ");
      for(int i=0; i<5;i++) {
         //Creating a Matcher object
         Matcher m = p.matcher(input[i]);  
         if(m.matches()) {
            System.out.println(m.group());
         }
      }
   }
}

Output

Enter 5 input strings:
sample string 1
sample string 2
11 sample string 3
22 sample string 4
43534 56353 636
Strings starting with digits:
11 sample string 3
22 sample string 4
43534 56353 636
raja
Published on 05-Feb-2021 10:25:53
Advertisements