- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to match a fixed set of characters using Java RegEx
The character classes allow you to accept a single character from a fixed set of characters. For example,
The expression “[tmp]” matches the characters t or, m or, p.
The expression “[^tp]” matches the characters other than t or, p.
Example 1
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example { public static void main(String args[]) { //Reading String from user System.out.println("Enter a String"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); //Regular expression to match the characters t or, m or, p String regex = "[tmp]"; //Compiling the regular expression Pattern pattern = Pattern.compile(regex); //Retrieving the matcher object Matcher matcher = pattern.matcher(input); int count = 0; while(matcher.find()) { count++; } System.out.println("Occurrences: "+count); } }
Output
Enter a String hello how are you welcome to tutorialspoint Occurrences :6
Example 2
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example { public static void main(String args[]) { //Reading String from user System.out.println("Enter a String"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); String regex = "[^abcdef]"; //Compiling the regular expression Pattern pattern = Pattern.compile(regex); //Retrieving the matcher object Matcher matcher = pattern.matcher(input); int count = 0; while(matcher.find()) { count++; } System.out.println("Occurrences :"+count); } }
Output
Enter a String Hello how are you welcome to tutorialspoint Occurrences :36
- Related Articles
- How to match a range of characters using Java regex
- How to match word characters using Java RegEx?
- How to match the regex meta characters in java as literal characters.
- How to match any character using Java RegEx
- How to match word boundaries using Java RegEx?
- How to match a non-word character using Java RegEx?
- How to match a white space equivalent using Java RegEx?
- How match a string irrespective of case using Java regex.
- How to match end of the input using Java RegEx?
- How to match end of a particular string/line using Java RegEx
- How to match beginning of a particular string/line using Java RegEx
- How to match digits using Java Regular Expression (RegEx)
- How to match non-word boundaries using Java RegEx?
- How to match a non-white space equivalent using Java RegEx?
- How to match the beginning of the input using Java RegEx?

Advertisements