How do I write character class subtraction regex?

You can use subtraction to negate one or more nested character classes. This example creates a single character class that matches everything from a to z, except the vowels (‘a’, ‘i’, ‘u’, ‘e’, ‘o’). This can be written in a subtraction pattern as [a-z&&[^aiueo]].

package org.kodejava.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharacterClassSubtractionDemo {
    public static void main(String[] args) {
        // Define regex that will search characters from 'a' to 'z'
        // and excluding vowels.
        String regex = "[a-z&&[^aiueo]]";

        // Compiles the given regular expression into a pattern and
        // Creates a matcher that will match the given input against
        // this pattern.
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher("The quick brown fox.");

        // Find every match and print it
        while (matcher.find()) {
            System.out.format("Text \"%s\" found at %d to %d.%n",
                    matcher.group(), matcher.start(), matcher.end());
        }
    }
}

Here are the result of the program:

Text "h" found at 1 to 2.
Text "q" found at 4 to 5.
Text "c" found at 7 to 8.
Text "k" found at 8 to 9.
Text "b" found at 10 to 11.
Text "r" found at 11 to 12.
Text "w" found at 13 to 14.
Text "n" found at 14 to 15.
Text "f" found at 16 to 17.
Text "x" found at 18 to 19.

How do I write character class intersection regex?

You can use the && operator to combine classes that define a sets of characters. It will only match characters common to both classes (intersection).

package org.kodejava.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharacterClassIntersectionDemo {
    public static void main(String[] args) {
        // Define regex that will search characters from 'a' to 'z'
        // and is a 'c' or 'a' or 't' character.
        String regex = "[a-z&&[cat]]";

        // Compiles the given regular expression into a pattern.
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(
                "The quick brown fox jumps over the lazy dog");

        // Find every match and print it
        while (matcher.find()) {
            System.out.format("Text \"%s\" found at %d to %d.%n",
                    matcher.group(), matcher.start(), matcher.end());
        }
    }
}

The program print the following result:

Text "c" found at 7 to 8.
Text "t" found at 31 to 32.
Text "a" found at 36 to 37.

How do I write union character class regex?

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.

How do I write range character class regex?

To define a character class that includes a range of values, put - metacharacter between the first and last character to be matched. For example [a-e]. You can also specify multiple ranges like this [a-zA-Z]. This will match any letter of the alphabet from a to z (lowercase) or A to Z (uppercase).

In the example below we are matching the word that begins with bat and ends with a single number that have a value range from 3 to 7.

package org.kodejava.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharacterClassesRangeClassDemo {
    public static void main(String[] args) {
        // Defines regex that will search all sequences of string
        // that begin with bat and number which range [3-7]
        String regex = "bat[3-7]";
        String input =
                "bat1, bat2, bat3, bat4, bat5, bat6, bat7, bat8";

        // Compiles the given regular expression into a pattern.
        Pattern pattern = Pattern.compile(regex);

        // Creates a matcher that will match the given input
        // against this pattern.
        Matcher matcher = pattern.matcher(input);

        // Find every match and prints it.
        while (matcher.find()) {
            System.out.format("Text \"%s\" found at %d to %d.%n",
                    matcher.group(), matcher.start(),
                    matcher.end());
        }
    }
}

The program will match the following string from the input:`

Text "bat3" found at 12 to 16.
Text "bat4" found at 18 to 22.
Text "bat5" found at 24 to 28.
Text "bat6" found at 30 to 34.
Text "bat7" found at 36 to 40.

How do I write negated character class regex?

A negation class is a character class that begins with a ^ metacharacter which will exclude a set of defined characters within a square brackets. For example the negation class h[^ao]t in the example below match only the word hit and exclude the words hat and hot.

package org.kodejava.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharacterClassesNegationClassDemo {
    public static void main(String[] args) {
        // Defines a regular expression that will search all
        // sequences of string that begin with 'h' and end with 't'
        // and have a middle letter except those appearing to the
        // right of the ^ character within the square brackets
        // ('a' and 'o')
        String regex = "h[^ao]t";

        // Compiles the pattern and obtains the matcher object.
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher =
                pattern.matcher("Wow, that hot hat will make a hit");

        // Find every match and prints it.
        while (matcher.find()) {
            System.out.format("Text \"%s\" found at %d to %d.%n",
                    matcher.group(), matcher.start(), matcher.end());
        }
    }
}

The program output the following result:

Text "hit" found at 30 to 33.