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 match a regex pattern in case-insensitive?

Finding the next subsequence of the input sequence that matches the pattern while ignoring the case of the string in regular expression can simply apply by create a pattern using compile(String regex, int flags) method and specifies a second argument with PATTERN.CASE_INSENSITIVE constant.

package org.kodejava.regex;

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

public class RegexIgnoreCaseDemo {
    public static void main(String[] args) {
        String sentence =
                "The quick brown fox and BROWN tiger jumps over the lazy dog";

        Pattern pattern = Pattern.compile("brown", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(sentence);

        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 "brown" found at 10 to 15.
Text "BROWN" found at 24 to 29.

How do I determine if a string match a pattern exactly?

If you want the entire string to match your regular expression pattern you can use the Matcher.matches() method. This method will return true if and only if entire input string matches with the matcher’s pattern.

If the pattern only needs to match the beginning of the string you can use the Matcher.lookingAt() method. You can find its example on the following address How do I check if a string starts with a pattern?.

package org.kodejava.regex;

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

public class MatcherMatchesExample {

    public static void main(String[] args) {
        String[] inputs = {
                "blue sky",
                "blue sea",
                "blue",
                "blue lagoon"
        };

        // Creates an instance of Pattern using the compile method.
        Pattern pattern = Pattern.compile("blue");

        int match = 0;
        for (String s : inputs) {
            // Creates a matcher that will match the given input
            // against this pattern.
            Matcher matcher = pattern.matcher(s);

            // Check if the input match the pattern exactly and
            // increment the match counter.
            if (matcher.matches()) {
                match++;
            }

        }

        System.out.println("Number of input matched: " + match);
    }
}

The code above will only match one input that match exactly with the pattern (“blue”), because the other three elements of the array has another word beside blue.

How do I check if a string starts with a pattern?

The example below demonstrate the Matcher.lookingAt() method to check if a string starts with a pattern represented by the Pattern class.

package org.kodejava.regex;

import java.util.Locale;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherLookingAtExample {

    public static void main(String[] args) {
        // Get the available countries
        Set<String> countries = new TreeSet<>();
        Locale[] locales = Locale.getAvailableLocales();
        for (Locale locale : locales) {
            countries.add(locale.getDisplayCountry());
        }

        // Create a Pattern instance. Look for a country that start with
        // "I" with an arbitrary second letter and have either "a" or "e"
        // letter in the next sequence.
        Pattern pattern = Pattern.compile("^I.[ae]");
        System.out.println("Country name which have the pattern of " +
                pattern.pattern() + ": ");

        // Find country name which prefix matches the matcher's pattern
        for (String country : countries) {
            // Create matcher object
            Matcher matcher = pattern.matcher(country);

            // Check if the matcher's prefix match with the matcher's
            // pattern
            if (matcher.lookingAt()) {
                System.out.println("Found: " + country);
            }
        }
    }
}

The following country names is printed as the result of the program above:

Country name which have the pattern of ^I.[ae]: 
Found: Iceland
Found: Iran
Found: Iraq
Found: Ireland
Found: Italy

How do I find and replace string?

The code below demonstrates the use Matcher.appendReplacement() and Matcher.appendTail() methods to create a program to find and replace a sub string within a string.

Another solution that can be used to search and replace a string can be found on the following example: How do I create a string search and replace using regex?.

package org.kodejava.regex;

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

public class AppendReplacementExample {
    public static void main(String[] args) {
        // Create a Pattern instance
        Pattern pattern = Pattern.compile("[Pp]en");

        // Create matcher object
        String input = "Please use your Pen to answer the question, " +
                "black pen is preferred.";
        Matcher matcher = pattern.matcher(input);
        StringBuilder builder = new StringBuilder();

        // Find and replace the text that match the pattern
        while (matcher.find()) {
            matcher.appendReplacement(builder, "pencil");
        }

        // This method reads characters from the input sequence, starting
        // at the beginning position, and appends them to the given string
        // builder. It is intended to be invoked after one or more
        // invocations of the appendReplacement method in order to copy
        // the remainder of the input sequence.
        matcher.appendTail(builder);

        System.out.println("Input : " + input);
        System.out.println("Output: " + builder);
    }
}

Here is the result of the above code:

Input : Please use your Pen to answer the question, black pen is preferred.
Output: Please use your pencil to answer the question, black pencil is preferred.