Java Reference
In-Depth Information
Here we assemble the string literal for the regular expression by concatenating six separate string
literals. Each of these corresponds to an easily identified part of the method call. If you count the left
parentheses, excluding the escaped parenthesis of course, you can also see that capturing group 1
corresponds with the method name, group 2 is the first method argument, and group 8 is the second
method argument.
We can put this in the example:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class TryCapturingGroups {
public static void main(String args[]) {
String regEx = "(Math.pow)" // Math.pow
+ "\\s*\\(\\s*" // Opening (
+ "(([a-zA-Z _ ]\\w*)|([+|-]?(\\d+(\\.\\d*)?)|(\\.\\d+)))" // First argument
+ "\\s*,\\s*" // Comma
+ "(([a-zA-Z _ ]\\w*)|([+|-]?(\\d+(\\.\\d*)?)|(\\.\\d+)))" // Second argument
+ "\\s*\\)"; // Closing (
String oldCode =
"double result = Math.pow( 3.0, 16.0);\n"
+ "double resultSquared = Math.pow(2 ,result );\n"
+ "double hypotenuse = Math.sqrt(Math.pow(2.0, 30.0)+Math.pow(2 , 40.0));\n";
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.toString());
System.out.println("New Code:\n"+newCode.toString());
}
}
You should get the 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));
Search WWH ::




Custom Search