smya.dsh smya.dsh - 7 months ago 20
Java Question

how to extract numeric values from input string in java

How can I extract only the numeric values from the input string?

For example, the input string may be like this:

String str="abc d 1234567890pqr 54897";


I want the numeric values only i.e,
"1234567890"
and
"54897"
. All the alphabetic and special characters will be discarded.

tbl tbl
Answer
String str=" abc d 1234567890pqr 54897";
Pattern pattern = Pattern.compile("\\w+([0-9]+)\\w+([0-9]+)");
Matcher matcher = pattern.matcher(str);
for(int i = 0 ; i < matcher.groupCount(); i++) {
  matcher.find();
  System.out.println(matcher.group());
}