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 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 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 simple character class regex?

A character class in the context of regular expression is a set of characters enclosed within a square brackets "[]". It specifies the characters that will successfully match a single character from the given input.

A simple class, the most basic form of character class, is formed simply by placing a set of characters side-by-side within square brackets. For example the regular expression b[ai]t will match the words "bit" or "bat" because the pattern defines a character class accepting either "i" or "a" as the middle character.

package org.kodejava.regex;

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

public class CharacterClassesSimpleClassDemo {
    public static void main(String[] args) {
        // Creating a simple class type of character classes.
        // The regular expression below will search all sequences
        // of string that begins with 'b', ends with 't' and have
        // a middle letter of 'a' or 'i'.
        String regex = "b[ai]t";

        // Compiles the pattern and obtains the matcher object.
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher =
                pattern.matcher("I'm a little bit afraid of bats " +
                        "but not cats.");

        // 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 print the following output:

Text "bit" found at 13 to 16.
Text "bat" found at 27 to 30.

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.