Java Reference
In-Depth Information
To keep things simple, you assume that a variable name is just any sequence of letters, digits, or underscores that
begins with a letter or an underscore. This avoids getting involved with qualified names. You can match a variable
name with the expression:
"[a-zA-Z_]\\w*"
You can therefore match either a variable name or a number with the pattern:
"(([a-zA-Z_]\\w*)|([+|-]?(\\d+(\\.\\d*)?)|(\\.\\d+)))"
This just ORs the two possibilities together and parenthesizes the whole thing so it is a capturing group.
A comma that may be surrounded by zero or more whitespace characters on either side follows the first argument.
You can match that with the pattern:
\\s*,\\s*
The pattern to match the second argument will be exactly the same as the first:
"(([a-zA-Z_]\\w*)|([+|-]?(\\d+(\\.\\d*)?)|(\\.\\d+)))"
Finally, this must be followed by a closing parenthesis that may or may not be preceded by whitespace:
\\s*\\)
You can put all this together to define the entire regular expression as the value for a String variable:
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 )
Here you 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.
You can put this in the following example:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class RearrangeText {
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";
Search WWH ::




Custom Search