Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Pattern toString() method in Java with examples
The Pattern class of the java.util.regex package is a compiled representation of a regular expression.
The toString() method of this class returns the string representation of the regular expression using which the current Pattern was compiled.
Example1
import java.util.Scanner;
import java.util.regex.Pattern;
public class Example {
public static void main( String args[] ) {
//Reading string value
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string");
String input = sc.nextLine();
//Regular expression to find digits
String regex = "(\d)";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Printing the regular expression
System.out.println("Compiled regular expression: "+pattern.toString());
//Verifying whether match occurred
if(pattern.matcher(input).find())
System.out.println("Given String contains digits");
else
System.out.println("Given String does not contain digits");
}
}
Output
Enter input string This 7est contain5 di9its in place of certain charac7er5 Compiled regular expression: (\d) Given String contains digits
Example 2
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
String regex = "Tutorialspoint$";
String input = "Hi how are you welcome to Tutorialspoint";
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
Match found regular expression: Tutorialspoint$
Advertisements