Character class

In this chapter you will learn:

  1. What is Character class
  2. Character class including all letters

What is Character class

A character class is a set of characters. A character class is specified by putting the characters in the class between brackets.

For example, the class [wxyz] matches w, x, y, or z.

To specify an inverted set, precede the characters with a ^. For example, [^wxyz] matches any character except w, x, y, or z.

You can specify a range of characters using a hyphen. For example, to specify a character class that will match the digits 1 through 9, use [1-9].

Character class including all letters

The code below creates a character class [a-z] which includes all lowercase letters.

import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*  j a  v  a 2 s. c  o  m*/
public class Main {
  public static void main(String args[]) {
    Pattern pat = Pattern.compile("[a-z]");
    Matcher mat = pat.matcher("this is a test.");
    while (mat.find()){
      System.out.println("Match: " + mat.group());
    }      
  }
}

The code above generates the following result.

From the result we can see that each of every single letter is matched, but the space is not matched.

Next chapter...

What you will learn in the next chapter:

  1. What are wildcard character in regular expressions
  2. How to dot wildcard character
Home » Java Tutorial » Regular Expressions
Regular Expression Processing
Normal characters
Character class
Wildcard Character
Quantifier
Wildcards and Quantifiers
Character class and quantifiers
Find sub string
Multiple subsequences
Replace all
Split