Java Reference
In-Depth Information
TRY IT OUT: Finding Numbers
This is similar to the code we have used in previous examples except that here we just list each substring
that is found to correspond to the pattern:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class FindingNumbers {
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);
String subStr = null;
while(m.find()) {
System.out.println(m.group());
// Output the
substring matched
}
}
}
FindingNumbers.java
This produces the following output:
256
16
-2.5
6.25
.243
0.1234
How It Works
Well, you found all the numbers in the string, so our regular expression works well, doesn't it? You can't
do that with the methods in the String class. The only new code item here is the method, group() ,
that you call in the while loop for the Matcher object, m . This method returns a reference to a String
object that contains the subsequence corresponding to the last match of the entire pattern. Calling the
group() method for the Matcher object m is equivalent to the expression str.substring(m.start(),
m.end()) .
Tokenizing a String
Search WWH ::




Custom Search