Java Reference
In-Depth Information
Pattern pattern = Pattern.compile(regEx);
Matcher m = pattern.matcher(oldCode);
StringBuffer newCode = new StringBuffer();
while(m.find()) {
m.appendReplacement(newCode, "$1\\($8,$2\\)");
}
m.appendTail(newCode);
System.out.println("Original Code:\n" + oldCode);
System.out.println("New Code:\n" + newCode);
}
}
RearrangeText.java
You should get the following output:
Original Code:
double result = Math.pow( 3.0, 16.0);
double resultSquared = Math.pow(2 ,result );
double hypotenuse = Math.sqrt(Math.pow(2.0, 30.0)+Math.pow(2 , 40.0));
New Code:
double result = Math.pow(16.0,3.0);
double resultSquared = Math.pow(result,2);
double hypotenuse = Math.sqrt(Math.pow(30.0,2.0)+Math.pow(40.0,2));
How It Works
You have defined the regular expression so that separate capturing groups identify the method name and both ar-
guments. As you saw earlier, the method name corresponds to group 1, the first argument to group 2, and the
second argument to group 8. You therefore define the replacement string to the
appendReplacement()
method as
"$1\\($8,$2\\)"
. The effect of this is to replace the text for each method call that is matched by the following
items in
Table 15-8
,
in sequence:
The text matching capturing group 1 — the method name
A left parenthesis
\\(
The text matching capturing group 8 — the second argument
$8
A comma
,
The text matching capturing group 2 — the first argument
$2
A right parenthesis
\\)
The call to
appendTail()
is necessary to ensure that any text left at the end of
oldCode
following the last match
for
regEx
gets copied to
newCode
.
In the process, you have eliminated any superfluous whitespace that was lying around in the original text.
USING A SCANNER
The
java.util.Scanner
class defines objects that use regular expressions to scan character input from a
variety of sources and present the input as a sequence of tokens of various primitive types or as strings. For
example, you can use a
Scanner
object to read data values of various types from a file or a stream, including