Method Boolean lookingAt()

The lookingAt()method attempts to match the input against the pattern, starting from the beginning of the input but without requiring that the entire region be matched against the pattern. The following code demonstrates it:

package example.regex; 

import java.util.regex.*;

class MatcherLookingatExample
{
public static void main (String[] args)
{

final Pattern pattern1 = Pattern.compile("master[a-z]*");
final Pattern pattern2 = Pattern.compile("master");
final Pattern pattern3 = Pattern.compile("regular");

String input = "mastering regular expressions";

Matcher matcher = pattern1.matcher(input);
System.out.printf("[%s] => [%s]: %s%n", input, matcher.pattern(),
matcher.lookingAt());

// update the matcher's pattern with a new pattern
matcher.usePattern(pattern2);
System.out.printf("[%s] => [%s]: %s%n", input, matcher.pattern(),
matcher.lookingAt());

// update the matcher's pattern with a new pattern
matcher.usePattern(pattern3);
System.out.printf("[%s] => [%s]: %s%n", input, matcher.pattern(),
matcher.lookingAt());

}
}

Upon compiling and running, the preceding code produces following output:

[mastering regular expressions] => [master[a-z]*]: true 
[mastering regular expressions] => [master]: true
[mastering regular expressions] => [regular]: false

You can see that the lookingAt()method returns true only when we supply patterns that are at the starting of the input, such as master[a-z]* and master, but returns false when we supply a pattern that is in the middle, such as regular.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.209.131