Java Reference
In-Depth Information
This will produce the output:
256
16
-2.5
6.25
.243
0.1234
How It Works
Well, we found all the numbers in the string so our regular expression works well, doesn't it? You can't
do that with the methods in the
String
class. The only new code item here is the method,
group()
,
that we call in the
while
loop for the
Matcher
object,
m
. This method returns a reference to a
String
object containing the subsequence corresponding to the last match of the entire pattern. Calling the
group()
method for the
Matcher
object,
m
, is equivalent to the expression
str.substring(m.start(),
m.end())
.
Search and Replace Operations
You can implement a search and replace operation very easily using regular expressions. Whenever you
call the
find()
method for a
Matcher
object, you can call the
appendReplacement()
method to
replace the subsequence that was matched. You create a revised version of the original string in a new
String Buffer object. There are two arguments to the
appendReplacement()
method. The first is a
reference to the
StringBuffer
object that is to contain the new string, and the second is the
replacement string for the matched text. We can see how this works by considering a specific example.
Suppose we define a string to be searched as:
String joke = "My dog hasn't got any nose.\n"
+"How does your dog smell then?\n"
+"My dog smells horrible.\n";
We now want to replace each occurrence of "
dog
" in the string by "
goat
". We first need a regular
expression to find "
dog
":
String regEx = "dog";
We can compile this into a pattern and create a
Matcher
object for the string
joke
:
Pattern doggone = Pattern.compile(regEx);
Matcher m = doggone.matcher(joke);
We are going to assemble a new version of
joke
in a
StringBuffer
object that we can create like this:
StringBuffer newJoke = new StringBuffer();