Java Reference
In-Depth Information
The pattern matches any word that starts with any character between 'q' and 'v' (the
[qrstuv] ) repeated any number of times (the “ * ”), followed by any single character (the . ),
and ending with the literal string “ing” . Using the tests array from the previous examples,
the matches are
ring matches [qrstuv]*.ing
trying matches [qrstuv]*.ing
Together with * , the + and ? metacharacters also allow for repetition in a regular
expression. The + matches the previous character or expression one or more times, while ?
matches the previous character or expression zero or one times. For example, the pattern x+
matches 1 or more x s. The pattern [aeiou]? matches any vowel zero or one times.
See if you can determine the output of the following statements:
23. Pattern p = Pattern.compile(“[0-4]+[a-z]*[5-9]?”);
24. String [] values = {“4a”, “112abc6”, “2345”, “01a”,
25. “a5” , “4a56” };
26. for(String value: values) {
27. Matcher m = p.matcher(value);
28. if(m.matches()) {
29. System.out.println(value + “ matches [0-4]+[a-z]*[5-9]?”);
30. }
31. }
Figure 4.10 explains the pattern “[0-4]+[a-z]*[5-9]?” and the strings that match it.
FIGURE 4.10
Using the +, ?, and * metacharacters
[f0410.eps]
[0 - 4] [a-z] * [5- 9] ?
The sequence must
start with 1 or more
digits between 0 and 4.
Next can come
any number of
lowercase letters
between a and z,
including no letters.
The sequence must
end with either
0 or 1 digits
between 5 and 9.
The string ”a5” does not match because it does not start with a digit between 0 and 4 .
The string ”4a56” does not match because it ends with two digits between 5 and 9 . The
other four strings in the values array match, so the output of the code is
4a matches [0-4]+[a-z]*[5-9]?
112abc6 matches [0-4]+[a-z]*[5-9]?
2345 matches [0-4]+[a-z]*[5-9]?
01a matches [0-4]+[a-z]*[5-9]?
Search WWH ::




Custom Search