
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
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()); }
Advertisements