Java Reference
In-Depth Information
Parentheses in a Regular Expression
Use parentheses to group together expressions in a regular expression. For example, the
pattern a*b+ matches any number of a 's followed by one or more b 's. Matches include
ab , aaaab , and b . Adding parentheses can change the pattern. For example, the pattern
(a*b)+ matches any number of a 's followed by one b , with that pattern repeated one or
more times. Matches include ab, abaabab, and babb.
The Pattern Character Classes
The Pattern class uses several predefi ned character classes that represent commonly used
character patterns in regular expressions. The exam objectives explicitly state knowledge of
the following three character classes:
\d , which denotes a digit; equivalent to [0-9]
\s , which denotes a whitespace character; equivalent to [ \t\n\x0B\f\r]
\w , which denotes a word character; equivalent to [a-zA-Z_0-9]
Because the syntax of the character classes starts with a backslash, in Java you must
escape them with an additional backslash. For example, the following regular expression
matches one or more digits:
String digits = “\\d+”;
See if you can determine the output of the following statements:
34. String s = “[A-Z]\\w*\\s+[A-Z]\\w+”;
35. Pattern x = Pattern.compile(s);
36. String [] names = {“John Doe”, “JohnDoe”, “John\tDoe”, “John doe”,
37. “J D”, “J D5”};
38. for(String name: names) {
39. Matcher m = x.matcher(name);
40. if(m.matches()) {
41. System.out.println(name + “ matches “ + s);
42. }
43. }
Figure 4.11 breaks down the regular expression on line 34.
Search WWH ::




Custom Search