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.example.util.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 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: Iraq
Found: Ireland
Found: Italy
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply