To create a single character class comprised of two or more separate character classes use unions. To create a union, simply nest one class inside the other, such as [0-3[7-9]]
.
package org.kodejava.regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CharacterClassUnionDemo {
public static void main(String[] args) {
// Defines regex that matches the number 0, 1, 2, 3, 7, 8, 9
String regex = "[0-3[7-9]]";
String input = "0123456789";
// Compiles the given regular expression into a pattern.
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
// Find matches and print it
while (matcher.find()) {
System.out.format("Text \"%s\" found at %d to %d.%n",
matcher.group(), matcher.start(),
matcher.end());
}
}
}
Here is the result of the program:
Text "0" found at 0 to 1.
Text "1" found at 1 to 2.
Text "2" found at 2 to 3.
Text "3" found at 3 to 4.
Text "7" found at 7 to 8.
Text "8" found at 8 to 9.
Text "9" found at 9 to 10.