# Use a character class in Java Regular Expressions

Java 8Object Oriented ProgrammingProgramming

#### Complete Java Programming Fundamentals With Sample Projects

98 Lectures 7.5 hours

#### Get your Java dream job! Beginners interview preparation

85 Lectures 6 hours

#### Core Java bootcamp program with Hands on practice

Featured

99 Lectures 17 hours

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

Live Demo

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());
}
Updated on 30-Jul-2019 22:30:24