Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between Matcher.lookingAt() and find()?

Tags:

java

regex

I am looking at Java regex tutorial, the title pretty much explains itself. It looks like Matcher.lookingAt() is trying to match the entire String. Is that true?

like image 341
Yibin Lin Avatar asked May 02 '15 22:05

Yibin Lin


People also ask

What is difference between matches () and find () in Java regex?

Difference between matches() and find() in Java Regex matcher() method. The matches() method returns true If the regular expression matches the whole text. If not, the matches() method returns false. Whereas find() search for the occurrence of the regular expression passes to Pattern.

What is find () in Java?

Matcher find() method in Java with Examples The find() method of Matcher Class attempts to find the next subsequence of the input sequence that find the pattern. It returns a boolean value showing the same. Syntax: public boolean find()

What does public boolean lookingAt () method do?

The lookingAt() method of Matcher Class attempts to match the pattern partially or fully in the matcher. It returns a boolean value showing if the pattern was matched even partially or fully starting from the start of the pattern. Parameters: This method do not takes any parameter.

What are matchers in Java?

A matcher is created from a pattern by invoking the pattern's matcher method. Once created, a matcher can be used to perform three different kinds of match operations: The matches method attempts to match the entire input sequence against the pattern.


1 Answers

The documentation for Matcher.lookingAt clearly explains the region lookingAt tries to match:

Like the matches method, this method always starts at the beginning of the region; unlike that method, it does not require that the entire region be matched.

So no, lookingAt does not require matching the whole string. Then what's the difference between lookingAt and find? From the Matcher Javadoc overview:

  • The matches method attempts to match the entire input sequence against the pattern.
  • The lookingAt method attempts to match the input sequence, starting at the beginning, against the pattern.
  • The find method scans the input sequence looking for the next subsequence that matches the pattern.

lookingAt always starts at the beginning, but find will scan for a starting position.

Viewed another way, matches has a fixed start and end, lookingAt has a fixed start but a variable end, and find has a variable start and end.

like image 156
Jeffrey Bosboom Avatar answered Sep 19 '22 00:09

Jeffrey Bosboom