Use Logical Operators
You can use the && operator to combine classes that define sets of characters. This is particularly useful when you use it combined with the negation operator(^). For example, if you want to specify that any uppercase consonant is acceptable, you could write the expression that matches this as “[A-CG-IM-Z]{2}”.
However, this can much more conveniently be expressed as “[A-Z&&[^D-FJ-L]]{2}”.
The pattern “[A-Z&&[^D-FJ-L]]{2}” produces the intersection (in other words, the characters common to both sets) of the set of characters “A” through “Z” with the set that is not a uppercase characters D,E,F,J,K and L. To put it another way, the uppercase characters D,E,F,J,K and L are subtracted from the set “A” through “Z” so you are left with just the uppercase consonants.
Program
Program Source
import java.util.regex.Pattern; import java.util.regex.Matcher; public class Javaapp { public static void main(String[] args) { Pattern pat = Pattern.compile("[A-Z&&[^D-FJ-L]]{2}"); Matcher mat = pat.matcher("AABBCCDDEEFFGGHHIIJJKK"); int i = 0; while(mat.find()) { i++; System.out.println(i+"th subsequence : "+mat.group()); } } }