Java Reference
In-Depth Information
Once a string is created, its contents cannot be changed. The methods
replace
,
replaceFirst
, and
replaceAll
return a new string derived from the original string
(without changing the original string!). Several versions of the
replace
methods are pro-
vided to replace a character or a substring in the string with a new character or a new
substring.
For example,
"Welcome".replace('e', 'A')
returns a new string,
WAlcomA
.
"Welcome".replaceFirst("e", "AB")
returns a new string,
WABlcome
.
"Welcome".replace("e", "AB")
returns a new string,
WABlcomAB
.
"Welcome".replace("el", "AB")
returns a new string,
WABcome
.
replace
replaceFirst
replace
replace
The
split
method can be used to extract tokens from a string with the specified delimiters.
For example, the following code
split
String[] tokens =
"Java#HTML#Perl"
.split(
"#"
);
for
(
int
i =
0
; i < tokens.length; i++)
System.out.print(tokens[i] +
" "
);
displays
Java HTML Perl
10.10.4 Matching, Replacing and Splitting by Patterns
Often you will need to write code that validates user input, such as to check whether the input
is a number, a string with all lowercase letters, or a Social Security number. How do you write
this type of code? A simple and effective way to accomplish this task is to use the regular
expression.
A
regular expression
(abbreviated
regex
) is a string that describes a pattern for matching
a set of strings. You can match, replace, or split a string by specifying a pattern. This is an
extremely useful and powerful feature.
Let us begin with the
matches
method in the
String
class. At first glance, the
matches
method is very similar to the
equals
method. For example, the following two statements both
evaluate to
true
.
why regular expression?
regular expression
regex
matches(regex)
"Java"
.matches(
"Java"
);
"Java"
.equals(
"Java"
);
However, the
matches
method is more powerful. It can match not only a fixed string, but
also a set of strings that follow a pattern. For example, the following statements all evaluate
to
true
:
"Java is fun"
.matches(
"Java.*"
)
"Java is cool"
.matches(
"Java.*"
)
"Java is powerful"
.matches(
"Java.*"
)
Java.*
in the preceding statements is a regular expression. It describes a string pattern that
begins with Java followed by
any
zero or more characters. Here, the substring matches any
zero or more characters.
The following statement evaluates to
true
.
"440-02-4534"
.matches(
"\\d{3}-\\d{2}-\\d{4}"
)
Here
\\d
represents a single digit, and
\\d{3}
represents three digits.
Search WWH ::
Custom Search