

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Matcher usePattern() method in Java with Examples
The java.util.regex.Matcher class represents an engine that performs various match operations. There is no constructor for this class, you can create/obtain an object of this class using the matches() method of the class java.util.regex.Pattern.
The usePattern() method of the Matcher class accepts a Pattern object representing a new regex pattern and uses it to find matches.
Example
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class UsePatternExample { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter input text: "); String input = sc.nextLine(); String regex = "[#%&*]"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Creating a Matcher object Matcher matcher = pattern.matcher(input); int count =0; while(matcher.find()) { count++; } //Retrieving Pattern used System.out.println("The are "+count+" special characters [# % & *] in the given text"); //Building a pattern to accept 5 t 6 characters Pattern newPattern = Pattern.compile("\\A(?=\\w{6,15}\\z)"); //Switching to new pattern matcher = matcher.usePattern(newPattern); if(matcher.find()) { System.out.println("Given input contain 6 to 15 characters"); } else { System.out.println("Given input doesn't contain 6 to 15 characters"); } } }
Output
Enter input text: #*mypassword& The are 3 special characters [# % & *] in the given text !!mypassword! Given input doesn't contain 6 to 15 characters
- Related Questions & Answers
- Matcher useTransparentBounds() method in Java with Examples
- Matcher hitEnd() method in Java with Examples
- Matcher start() method in Java with Examples
- Matcher matches() method in Java with Examples
- Pattern matcher() method in Java with examples
- Matcher pattern() method in Java with Examples
- Matcher replaceAll() method in Java with Examples
- Matcher replaceFirst() method in Java with Examples
- Matcher requireEnd() method in Java with Examples
- Matcher reset() method in Java with Examples
- Matcher toString() method in Java with Examples
- Matcher appendTail() method in Java with Examples
- Matcher group() method in Java with Examples
- Matcher groupCount() method in Java with Examples
- Matcher appendReplacement() method in Java with Examples
Advertisements