Java Reference
In-Depth Information
• Class
Pattern
(p. 631) represents a regular expression.
• Class
Matcher
(p. 631) contains a regular-expression pattern and a
CharSequence
in which to
search.
•
CharSequence
is an interface (p. 631)
that allows read access to a sequence of characters. Both
String
and
StringBuilder
implement this interface, so they can be used with class
Matcher
.
• If a regular expression will be used only once, static
Pattern
method
matches
(p. 631) takes a string
that specifies the regular expression and a
CharSequence
on which to perform the match. This
method returns a
boolean
indicating whether the search object matches the regular expression.
• If a regular expression will be used more than once, it's more efficient to use static
Pattern
meth-
od
compile
(p. 631)
to create a specific
Pattern
object for that regular expression. This method
receives a string representing the pattern and returns a new
Pattern
object.
•
Pattern
method
matcher
(p. 631) receives a
CharSequence
to search and returns a
Matcher
ob-
ject.
Matcher
method
matches
(p. 631) performs the same task as
Pattern
method
matches
but
without arguments.
•
Matcher
method
find
(p. 631)
attempts to match a piece of the search object to the search pat-
tern. Each call to this method starts at the point where the last call ended, so multiple matches
can be found.
•
Matcher
method
lookingAt
(p. 631) performs the same as
find
, except that it always starts from
the beginning of the search object and will always find the first match if there is one.
•
Matcher
method
group
(p. 632)
returns the string from the search object that matches the search
pattern. The string returned is the one that was last matched by a call to
find
or
lookingAt
.
Self-Review Exercises
14.1
State whether each of the following is
true
or
false
. If
false
, explain why.
a)
When
String
objects are compared using
==
, the result is
true
if the
String
s contain
the same values.
b)
A
String
can be modified after it's created.
14.2
For each of the following, write a single statement that performs the indicated task:
a)
Compare the string in
s1
to the string in
s2
for equality of contents.
b)
Append the string
s2
to the string
s1
, using
+=
.
c)
Determine the length of the string in
s1
.
Answers to Self-Review Exercises
14.1
a)
False. String objects are compared using operator == to determine whether they're the
same object in memory.
b)
False.
String
objects are immutable and cannot be modified after they're created.
StringBuilder
objects can be modified after they're created.
14.2
a)
s1.equals(s2)
b)
s1 += s2;
c)
s1.length()
Exercises
14.3
(Comparing
String
s)
Write an application that uses
String
method
compareTo
to compare
two strings input by the user. Output whether the first string is less than, equal to or greater than
the second.