Java Reference
In-Depth Information
public static void main(String[] args) {
String str = "Smith , where Jones had had 'had', had had 'had
String regex = "had";
System.out.println("String is:\n" + str + "\nToken sought is: " +
Pattern had = Pattern.compile(regex);
Scanner strScan = new Scanner(str);
int hadCount = 0;
while(strScan.hasNext()) {
if(strScan.hasNext(had)) {
System.out.println("Token found!: " +;
} else {
System.out.println("Token is
: " +;
System.out.println(hadCount + " instances of \"" + regex + "\"
were found.");
This program produces the following output:
String is:
Smith , where Jones had had 'had', had had 'had had'.
Token sought is: had
Token is : Smith
Token is : ,
Token is : where
Token is : Jones
Token found!: had
Token found!: had
Token is : 'had',
Token found!: had
Token found!: had
Token is : 'had
Token is : had'.
4 instances of "had" were found.
How It Works
After defining the string to be scanned and the regular expression that defines the form of a token,
you compile the regular expression into a Pattern object. Passing a Pattern object to the hasNext()
method (or the next() method) is more efficient than passing the original regular expression when you
are calling the method more than once. When you pass a regular expression as a String object to the
hasNext() method, the method must compile it to a pattern before it can use it. If you compile the regu-
lar expression first and pass the Pattern object as the argument, the compile operation occurs only once.
Search WWH ::

Custom Search