下面的示例演示Matcher.lookingAt()检查字符串是否以Pattern类表示的模式开头的方法。
package org.nhooo.example.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) { // 具有任意第二个字母的“ I”,并且具有“ a”或“ e”具有任意第二个字母的“ I”,并且具有“ a”或“ e”获取可用的国家 Set<String> countries = new TreeSet<>(); Locale[] locales = Locale.getAvailableLocales(); for (Locale locale : locales) { countries.add(locale.getDisplayCountry()); } //创建一个Pattern实例。寻找一个以...开头的国家 // 具有任意第二个字母的“ I”,并且具有“ a”或“ e”"I" with an arbitrary second letter and have either "a" or "e" // 具有任意第二个字母的“ I”,并且具有“ a”或“ e”letter in the next sequence. Pattern pattern = Pattern.compile("^I.[ae]"); System.out.println("Country name which have the pattern of " + pattern.pattern() + ": "); // 具有任意第二个字母的“ I”,并且具有“ a”或“ e”Find country name which prefix matches the matcher's pattern for (String country : countries) { // 具有任意第二个字母的“ I”,并且具有“ a”或“ e”Create matcher object Matcher matcher = pattern.matcher(country); // 具有任意第二个字母的“ I”,并且具有“ a”或“ e”Check if the matcher's prefix match with the matcher's // 具有任意第二个字母的“ I”,并且具有“ a”或“ e”pattern if (matcher.lookingAt()) { System.out.println("Found: " + country); } } } }
通过以上程序,将打印以下国家名称:
Country name which have the pattern of ^I.[ae]: Found: Iceland Found: Iraq Found: Ireland Found: Italy