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.

How do I split up string using regular expression?

This code snippet uses the java.util.regex.Pattern.split() method to split-up input string separated by commas or whitespaces (spaces, tabs, new lines, carriage returns, form feeds).

package org.kodejava.regex;

import java.util.regex.Pattern;

public class RegexSplitExample {
    public static void main(String[] args) {
        // Pattern for finding commas, whitespaces (spaces, tabs, new lines,
        // carriage returns, form feeds).
        String pattern = "[,\\s]+";
        String colors = """
                Red,White, Blue   Green        Yellow,
                Orange Pink""";

        Pattern splitter = Pattern.compile(pattern);
        String[] results = splitter.split(colors);

        for (String color : results) {
            System.out.format("Color = \"%s\"%n", color);
        }
    }
}

The result of our code snippet is:

Color = "Red"
Color = "White"
Color = "Blue"
Color = "Green"
Color = "Yellow"
Color = "Orange"
Color = "Pink"

How do I create a string search and replace using regex?

In this example you’ll see how we can create a small search and replace program using the regular expression classes in Java. The code below will replace all the brown words to red.

package org.kodejava.regex;

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

public class StringReplace {
    public static void main(String[] args) {
        String source = "The quick brown fox jumps over the brown lazy dog.";
        String find = "brown";
        String replace = "red";

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

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

        // Replaces every subsequence of the input sequence that matches
        // the pattern with the given replacement string.
        String output = matcher.replaceAll(replace);

        System.out.println("Source = " + source);
        System.out.println("Output = " + output);
    }
}

The result of the code snippet is:

Source = The quick brown fox jumps over the brown lazy dog.
Output = The quick red fox jumps over the red lazy dog.