Thursday, August 5, 2010

Regex: Regex2.java

Courtesy of SCJP Sun® Certified Programmer for Java™ 6 Study Guide Exam (310-065) (9780071591065) 
Chapter 6, Question 1












This program compiles and runs as long as you provide a pattern, and a string where you search the pattern.

If you invoke  

java Regex2 "\d*" ab34ef

 
You are asking the JVM to look for 0 or more digits in ab34ef, then print the index where the matching pattern begins, and the matching pattern itself.

a b 3 4 e f
0 1 2 3 4 5

a and b are not digits, so 01 is output. 3 and 4 are both digits; since * denotes 0 or more, and is a greedy quantifier, 34 is considered a pattern, which starts at index 2, so we have 234. Next, we have e and f that are located at index 4 and 5 respectively. Finally the program iterates once more to find a blank, which comes under 0 or more digits, so 6 is printed. Final output:

01234456

No comments:

Post a Comment