bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths

Loading lesson path

Learn/Java/Java Reference
Java•Java Reference

Java Scanner findWithinHorizon() Method

❮ Scanner Methods

Example

Find an email address in a line of text:

// Create a scanner object Scanner myObj = new Scanner("Please send an email to info@example.com for more details.");
// Get the email address with a pattern String email = myObj.findWithinHorizon("[a-zA-Z]+@[a-zA-Z]+.[a-zA-Z]{2,}", 0);
// Show the email if found
if (email != null) {
 System.out.println(email);
} else {
System.out.println("No email found");
}

Definition and Usage

The findWithinHorizon() method searches through a specified number of characters for the first match of a regular expression provided by a Pattern object or a string. If a match is not found then it returns null .

The number of characters to search is specified by the horizon parameter, if it is set to zero then it continues searching without limit.

If a match is found the scanner advances to the first character following the match.

Learn more about the regular expressions in our Java RegEx tutorial .

One of the following

public String findWithinHorizon(Pattern
pattern , int
horizon )
public String findWithinHorizon(String
pattern , int
horizon )

Parameter Values

ParameterDescription
patternRequired. A string or Pattern object. Specifies the regular expression used in the search.
horizonRequired. Specifies a limit for how far ahead to search. If the value is zero then there is no limit.

Technical Details

Returns:A String containing the matched text or null if no match was found.
Throws:IllegalStateException - If the scanner has been closed. IllegalArgumentException - If the horizon parameter is negative.

❮ Scanner Methods

Previous

Java Scanner findInLine() Method

Next

Java Scanner hasNext() Method