- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Use a character class in Java Regular Expressions
A character class is set of characters that are enclosed inside square brackets. The characters in a character class specify the characters that can match with a character in an input string for success. An example of a character class is [a-z] which denotes the alphabets a to z.
A program that demonstrates a character class in Java Regular Expressions is given as follows:
Example
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Demo { public static void main(String args[]) { Pattern p = Pattern.compile("[a-z]+"); Matcher m = p.matcher("the sky is blue"); System.out.println("The input string is: the sky is blue"); System.out.println("The Regex is: [a-z]+"); System.out.println(); while (m.find()) { System.out.println("Match: " + m.group()); } } }
Output
The input string is: the sky is blue The Regex is: [a-z]+ Match: the Match: sky Match: is Match: blue
Now let us understand the above program.
The subsequence “[a-z]+” is searched in the string sequence "the sky is blue". Here a character class is used i.e. [a-z] which denotes the alphabets a to z. The find() method is used to find if the subsequence is in the input sequence and the required result is printed. A code snippet which demonstrates this is as follows:
Pattern p = Pattern.compile("[a-z]+"); Matcher m = p.matcher("the sky is blue"); System.out.println("The input string is: the sky is blue"); System.out.println("The Regex is: [a-z]+"); System.out.println(); while (m.find()) { System.out.println("Match: " + m.group()); }
- Related Articles
- Character class: intersection - Java regular expressions
- Character class: subtraction - Java regular expressions
- Character class: Negation - Java regular expressions
- Character class: range - Java regular expressions
- Character class: union - Java regular expressions
- Explain character classes in Java regular expressions
- PatternSyntaxException class in Java regular expressions\n
- Use the ? quantifier in Java Regular Expressions
- A greedy qualifier in Java Regular Expressions
- A Reluctant qualifier in Java Regular Expressions
- Java Regular Expressions Tutorial
- How to use regular expressions in a CSS locator?
- Greedy quantifiers Java Regular expressions in java.
- Back references in Java regular expressions
- Regular Expressions syntax in Java Regex

Advertisements