The lookingAt() Method: Prefix Matching
You'll learn how to check if a string starts with a pattern without requiring the entire string to match.
What Is lookingAt()?
After creating a Matcher from a Pattern, you have several ways to test your input. While matches() requires the entire string to match and find() searches anywhere in the string, lookingAt() checks if the input begins with your pattern—but doesn't care what comes after.
Think of it like this: matches() is like checking if someone read an entire book exactly as written. find() is like searching for a specific phrase anywhere in the book. lookingAt() is like checking if the book starts with a particular opening line—the rest of the book can be anything.
How It Works
import java.util.regex.*;
Pattern pattern = Pattern.compile("Java");
Matcher matcher = pattern.matcher("JavaScript is popular");
boolean startsWithJava = matcher.lookingAt(); // true
The pattern "Java" appears at the beginning of "JavaScript is popular", so lookingAt() returns true. The fact that "Script is popular" follows doesn't matter.
Compare this to matches():
Matcher matcher2 = pattern.matcher("JavaScript is popular");
boolean fullMatch = matcher2.matches(); // false
This returns false because the entire string doesn't match "Java" exactly.
Practical Example
Pattern httpPattern = Pattern.compile("https?://");
Matcher urlMatcher = httpPattern.matcher("http://example.com/page");
if (urlMatcher.lookingAt()) {
System.out.println("Valid URL prefix detected");
}
Key Takeaway: Use lookingAt() when you need to verify that input begins with a specific pattern, but don't need the entire string to match—it's perfect for prefix validation and protocol checking.