Java Reference
In-Depth Information
11. }
12. if(m2.matches()) {
13. System.out.println(“goodbye is a match”);
14. }
The regular expression ”hello” on line 5 is an example of a string literal pattern, the
simplest pattern in regular expressions. A character sequence matches the regular expres-
sion ”hello” only if the character sequence is ”hello” . The Pattern object on line 6 rep-
resents the compiled pattern. Two Matcher objects are instantiated for the pattern: ”hello”
and ”goodbye” . Line 9 is true because “hello” matches the pattern, and line 12 is false
because “goodbye” does not match the pattern. The output of the code is
hello is a match
Regular Expression Metacharacters
A typical regular expression is more complex than a string literal like “hello”. A special
set of characters called metacharacters is used to specify wildcards, repetition, ranges,
and more. Table 4.3 shows the metacharacters specifi cally mentioned in the SCJP exam
objectives.
TABLE 4.3
Metacharacters of Regular Expressions
Metacharacter
Description
. (dot)
Any character
*
Match the preceding character any number of times
+
Match the previous character one or more times
?
Match the previous character 0 or 1 times only
\d
A digit 0-9
\s
A whitespace character
\w
A word character (any lowercase or uppercase letter, the underscore char-
acter, or any digit)
[ ]
Match anything inside the square brackets for one character position once
( )
Use parentheses for grouping together search expressions
Search WWH ::




Custom Search