Java Reference
In-Depth Information
We are still missing something though. What about the value .25 or the value -3? The optional sign in
front of a number is easy so let's deal with that first. To express the possibility that - or + can appear we
can use [-|+] , and since this either appears or it doesn't, we can extend it to [+|-]? . So to add the
possibility of a sign we can write the expression as:
"[+|-]?\\d+(\\.\\d*)?"
We have to be careful how we allow for numbers beginning with a decimal point. We can't allow a sign
followed by a decimal point or just a decimal point by itself to be interpreted as a number so we can't
say a number starts with zero or more digits or that the leading digits are optional. We could define a
separate expression for numbers without leading digits like this:
"[+|-]?\\.\\d+"
Here there is an optional sign followed by a decimal point and at least one digit. With the other
expression there is also an optional sign so we can combine these into a single expression to recognize
either form, like this:
"[+|-]?(\\d+(\\.\\d*)?)|(\\.\\d+)"
This regular expression identifies substrings with an optional plus or minus sign followed by either a
substring defined by " \\d+(\\.\\d*)? " or a substring defined by " \\.\\d+ " . You might be
tempted to use square brackets instead of parentheses here, but this would be quite wrong as square
brackets define a set of characters, so any single character from the set is a match.
That was probably a bit more work than you anticipated but it's often the case that things that look
simple at first sight can turn out to be a little tricky. Let's try that out in an example.
Try It Out - Finding Integers
This is similar to the code we have used in previous examples except that here we will just list each
substring that is found to correspond to the pattern:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class FindingIntegers {
public static void main(String args[]) {
String regEx = "[+|-]?(\\d+(\\.\\d*)?)|(\\.\\d+)" ;
String str = "256 is the square of 16 and -2.5 squared is 6.25 " +
"and -.243 is less than 0.1234.";
Pattern pattern = Pattern.compile(regEx);
Matcher m = pattern.matcher(str);
int i = 0;
String subStr = null;
while(m.find())
System.out.println(m.group()); // Output the substring matched
}
}
Search WWH ::




Custom Search