Character class
In this chapter you will learn:
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: