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

Patternizing the toString() method in Java with examples

java.util.regexOf the packagePatternIs the compiled representation of a regular expression.

This classtoString()The method returns the string representation of the regular expression used to compile the current Pattern.

Example1

import java.util.Scanner;
import java.util.regex.Pattern;
public class Example {
   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 for finding numbers
      String regex = "(\\d)";
      //Compile regular expression
      Pattern pattern = Pattern.compile(regex);
      //Print regular expression
      System.out.println("Compiled regular expression: ");+pattern.toString());
      //Verify if a match occurs
      if(pattern.matcher(input).find())
         System.out.println("Given String contains digits");
      else
         System.out.println("Given String does not contain digits");
   }
}

Output result

Enter input string
This 7est contain5 di9its in place of certain character7er5
Compiled regular expression: (\d)
Given String contains digits

Example2

import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      String regex = "w3codebox$";
      String input = "Hi how are you welcome to w3codebox";
      Pattern pattern = Pattern.compile(regex);
      Matcher match = pattern.matcher(input);
      int count = 0;
      if(match.find())
         System.out.println("Match found");
      else
         System.out.println("Match not found");
      System.out.println("regular expression: ");+pattern.toString());
   }
}

Output result

Match found
regular expression: w3codebox$