Java Reference
In-Depth Information
The key to the whole problem is to devise a regular expression with capturing groups for the bits we want to
switch - the two arguments. Be warned - this is going to get a little messy; not difficult though - just messy.
We can define the first part of the regular expression that will find the sequence " Math.pow( ". at any
point where we want to allow an arbitrary number of whitespace characters we can use the sequence
\\s* . You will recall that \\s in a Java string specifies the predefined character class \s which is
whitespace. The * quantifier specifies zero or more of them. If we allow for whitespace between
Math.pow and the opening parenthesis for the arguments, and some more whitespace after the opening
parenthesis, the regular expression will be:
"(Math.pow)\\s*\\(\\s*"
We have to specify the opening parenthesis by " \\( " since an opening parenthesis is a meta-character
so we have to escape it.
This is followed by the first argument, which we said could be a number or a variable name. We created
the expression to identify a number earlier. It was:
"[+|-]?(\\d+(\\.\\d*)?)|(\\.\\d+)"
To keep things simple we will assume that a variable name is just any sequence of letters, digits, or
underscores that begins with a letter or an underscore, so we won't get involved with qualified names.
We can match a variable name with the expression:
"[a-zA-Z _ ]\\w*"
We 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 will be a capturing group.
A comma that may be surrounded by zero or more whitespace characters on either side follows the first
argument. We 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*\\)
We can put all this together to define the entire regular expression as 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 (
Search WWH ::




Custom Search