Java Reference
In-Depth Information
The
parse
method throws a
ParseException
if the beginning of the string
cannot be parsed. As with the
parse
method in
NumberFormat
, the
parse
method in
DateFormat
successfully parses a string if the beginning of the
string is in the proper format.
The
DateFormat
class is useful when you develop Java applications that need to
work with formatted dates and times. The next section discusses some useful classes
for working with regular expressions.
Regular Expressions
A
regular expression
is a sequence of characters that describes a pattern of characters.
The pattern describes a set of strings based on common characteristics. The syntax for a
regular expression is not unique to Java, and they are used in many different programming
languages. Java uses the
Pattern
and
Matcher
classes in the
java.util.regex
package for
using regular expressions in your Java applications.
For the exam you should be able to write code that uses the
Pattern
and
Matcher
classes
and the
String.split
method. You also need to be able to “recognize and use regular
expression patterns for matching (limited to:
.
(dot),
*
(star), + (plus),
?
,
\d
,
\s
,
\w
,
[]
,
()
).”
The objectives specifi cally state that what you need to know about “the use of
*
,
+
, and
?
will be limited to greedy quantifi ers, and the parentheses operator will only be used as a
grouping mechanism, not for capturing content during matching.” This section discusses
these topics in detail, starting with a discussion on the
Pattern
and
Matcher
classes.
The
Pattern
and
Matcher
Classes
The
Pattern
class represents a compiled regular expression. You do not instantiate a
Pat-
tern
object; instances are obtained from the static
compile
method defi ned in the
Pattern
class
public static Pattern compile(String regex)
.
Regular expressions need to be compiled into a pattern. The resulting
Pattern
object is
used to obtain a
Matcher
instance. A
Matcher
object represents the engine that performs
the actual parsing on the character sequence to see if it matches the pattern.
The following statements represent a typical usage of the
Pattern
and
Matcher
classes:
5. String regex = “hello”;
6. Pattern pattern = Pattern.compile(regex);
7. Matcher m1 = pattern.matcher(“hello”);
8. Matcher m2 = pattern.matcher(“goodbye”);
9. if(m1.matches()) {
10. System.out.println(“hello is a match”);
Search WWH ::
Custom Search