如果您希望整个字符串与您的正则表达式模式匹配,则可以使用该Matcher.matches()方法。true当且仅当整个输入字符串与匹配器的模式匹配时,此方法才会返回。
如果模式仅需要匹配字符串的开头,则可以使用Matcher.lookingAt()方法。您可以在以下地址找到其示例。如何检查字符串是否以模式开头?
package org.nhooo.example.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"
};
// 使用compile方法创建Pattern的实例。
Pattern pattern = Pattern.compile("blue");
int match = 0;
for (String s : inputs) {
// 创建将匹配给定输入的匹配器
// 反对这种模式。
Matcher matcher = pattern.matcher(s);
// 检查输入是否与模式完全匹配,然后
// 增加比赛计数器。
if (matcher.matches()) {
match++;
}
}
System.out.println("Number of input matched: " + match);
}
}上面的代码将只匹配与模式(“ blue”)完全匹配的一个输入,因为数组的其他三个元素在blue之外还有另一个单词。