smya.dsh
smya.dsh

Reputation: 661

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.

Upvotes: 13

Views: 93923

Answers (16)

Koncorde
Koncorde

Reputation: 1

String str = "abc34bfg 56tyu";

str = str.replaceAll("[^0-9]","");

output: 3456

Upvotes: 0

Keshav Agarawal
Keshav Agarawal

Reputation: 1

String str = "abc d 1234567890pqr 54897";
str = str.replaceAll("[^\\d ]", "");

The result will be "1234567890 54897".

Upvotes: 0

Bohemian
Bohemian

Reputation: 425033

You want to discard everything except digits and spaces:

String nums = input.replaceAll("[^0-9 ]", "").replaceAll(" +", " ").trim();

The extra calls clean up doubled and leading/trailing spaces.

If you need an array, add a split:

String[] nums = input.replaceAll("[^0-9 ]", "").trim().split(" +");

Upvotes: 2

Ashish Saini
Ashish Saini

Reputation: 2318

 public static String convertBudgetStringToPriceInteger(String budget) {
    if (!AndroidUtils.isEmpty(budget) && !"0".equalsIgnoreCase(budget)) {
        double numbers = getNumericFromString(budget);
        if( budget.contains("Crore") ){
            numbers= numbers* 10000000;
        }else if(budget.contains("Lac")){
            numbers= numbers* 100000;
        }
        return removeTrailingZeroesFromDouble(numbers);
    }else{
        return "0";
    }
}

Get numeric value from alphanumeric string

 public static double getNumericFromString(String string){
    try {
        if(!AndroidUtils.isEmpty(string)){
            String commaRemovedString = string.replaceAll(",","");
            return Double.parseDouble(commaRemovedString.replaceAll("[A-z]+$", ""));
            /*return Double.parseDouble(string.replaceAll("[^[0-9]+[.[0-9]]*]", "").trim());*/

        }
    }catch (NumberFormatException e){
        e.printStackTrace();
    }
    return 0;
}

For eg . If i pass 1.5 lac or 15,0000 or 15 Crores then we can get numeric value from these fucntion . We can customize string according to our needs. For eg. Result would be 150000 in case of 1.5 Lac

Upvotes: 0

Az.MaYo
Az.MaYo

Reputation: 1106

        String line = "This order was32354 placed 343434for 43411 QT ! OK?";
        String regex = "[^\\d]+";

        String[] str = line.split(regex);
        String required = "";
        for(String st: str){
            System.out.println(st);
        }

By above code you will get all the numeric values. then you can merge them or what ever you wanted to do with those numeric values.

Upvotes: 2

Rahul
Rahul

Reputation: 11

public class ExtractNum

{

  public static void main(String args[])

  {

   String input = "abc d 1234567890pqr 54897";

   String digits = input.replaceAll("[^0-9.]","");

   System.out.println("\nGiven Number is :"+digits);

  }

 }

Upvotes: 0

ak1
ak1

Reputation: 104

If you do not want to use regex,

String str = " abc d 1234567890pqr 54897";

char[] chars = new char[str.length()];

int i = 0;
for (int j = 0; j < str.length(); j++) {
    char c = str.charAt(j);
    if (Character.isDigit(c)) {
        chars[i++] = c;
        if (j != chars.length - 1)
            continue;
    }
    if (chars[0] == '\0')
        continue;
    String num = new String(chars).trim();
    System.out.println(num);
    chars = new char[str.length()];
    i = 0;

}

Output : 1234567890 54897

Upvotes: 2

Yura
Yura

Reputation: 1813

Example using java Scanner class

import java.util.Scanner;

Scanner s = new Scanner( "abc d 1234567890pqr 54897" );
s.useDelimiter( "\\D+" );
while ( s.hasNextInt() ){
    s.nextInt(); // get int
}

Upvotes: 2

laksys
laksys

Reputation: 3237

Just extract the digits

String str=" abc d 1234567890pqr 54897";        

for(int i=0; i<str.length(); i++)
    if( str.charAt(i) > 47 && str.charAt(i) < 58)
        System.out.print(str.charAt(i));

Another version

String str=" abc d 1234567890pqr 54897";        
boolean flag = false;
for(int i=0; i<str.length(); i++)
    if( str.charAt(i) > 47 && str.charAt(i) < 58) {
        System.out.print(str.charAt(i));
        flag = true;
    } else {
        System.out.print( flag ? '\n' : "");
        flag = false;
    }

Upvotes: 1

Pawel Solarski
Pawel Solarski

Reputation: 1048

public static List<String> extractNumbers(String string) {
    List<String> numbers = new LinkedList<String>();
    char[] array = string.toCharArray();
    Stack<Character> stack = new Stack<Character>();

    for (int i = 0; i < array.length; i++) {
        if (Character.isDigit(array[i])) {
            stack.push(array[i]);
        } else if (!stack.isEmpty()) {
            String number = getStackContent(stack);
            stack.clear();
            numbers.add(number);
        }
    }
    if(!stack.isEmpty()){
        String number = getStackContent(stack);
        numbers.add(number);            
    }
    return numbers;
}

private static String getStackContent(Stack<Character> stack) {
    StringBuilder sb = new StringBuilder();
    Enumeration<Character> elements = stack.elements();
    while (elements.hasMoreElements()) {
        sb.append(elements.nextElement());
    }
    return sb.toString();
}

public static void main(String[] args) {
    String str = " abc d 1234567890pqr 54897";
    List<String> extractNumbers = extractNumbers(str);
    for (String number : extractNumbers) {
        System.out.println(number);
    }
}

Upvotes: 1

tbl
tbl

Reputation: 771

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());
}

Upvotes: 14

big zero
big zero

Reputation: 610

You can use str = str.replaceAll("replaced_string","replacing_string");

String str=" abc d 1234567890pqr 54897";
String str_rep1=" abc d ";
String str_rep2="pqr ";
String result1=str.replaceAll("", str_rep1);
String result2=str.replaceAll(",",str_rep2);

also what npinti suggests is fine to work with.

Upvotes: 2

Paulius Matulionis
Paulius Matulionis

Reputation: 23415

Split your string into char array using yourString.toCharArray(); Then iterate through the characters and use Character.isDigit(ch); to identify if this is the numeric value. Or iterate through whole string and use str.charAt(i). For e.g:

public static void main(String[] args) {
    String str = "abc d 1234567890pqr 54897";
    StringBuilder myNumbers = new StringBuilder();
    for (int i = 0; i < str.length(); i++) {
        if (Character.isDigit(str.charAt(i))) {
            myNumbers.append(str.charAt(i));
            System.out.println(str.charAt(i) + " is a digit.");
        } else {
            System.out.println(str.charAt(i) + " not a digit.");
        }
    }
    System.out.println("Your numbers: " + myNumbers.toString());
}

Upvotes: 8

npinti
npinti

Reputation: 52185

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));
}

Upvotes: 23

Reimeus
Reimeus

Reputation: 159784

You could do something like:

Matcher m = Pattern.compile("\\d+").matcher(str);
while (m.find()) {
   System.out.println(m.group(0));
}

Upvotes: 5

Hank Gay
Hank Gay

Reputation: 71939

You could split the string on spaces to get the individual entries, loop across them, and try to parse them with the relevant method on Integer, using a try/catch approach to handle the cases where parsing it is as a number fails. That is probably the most straight-forward approach.

Alternatively, you can construct a regex to match only the numbers and use that to find them all. This is probably far more performant for a big string. The regex will look something like `\b\d+\b'.

UPDATE: Or, if this isn't homework or similar (I sort of assumed you were looking for clues to implementing it yourself, but that might not have been valid), you could use the solution that @npinti gives. That's probably the approach you should take in production code.

Upvotes: 1

Related Questions