Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to extract numeric values from input string in java

Tags:

java

string

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.

like image 215
smya.dsh Avatar asked Aug 31 '12 13:08

smya.dsh


People also ask

How do I extract a number from a string?

The number from a string in javascript can be extracted into an array of numbers by using the match method. This function takes a regular expression as an argument and extracts the number from the string. Regular expression for extracting a number is (/(\d+)/).


2 Answers

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());
}
like image 172
tbl Avatar answered Sep 29 '22 08:09

tbl


You could use the .nextInt() method from the Scanner class:

Scans the next token of the input as an int.

Alternatively, you could also do something like so:

String str=" abc d 1234567890pqr 54897";

Pattern p = Pattern.compile("(\\d+)");
Matcher m = p.matcher(str);
while(m.find())
{
    System.out.println(m.group(1));
}
like image 33
npinti Avatar answered Sep 29 '22 07:09

npinti