13

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.

3
  • all the alphabets will be discarded - you mean instead Commented Aug 31, 2012 at 13:16
  • yes. alphabets and special characters to be discarded i want only those numbers. Commented Aug 31, 2012 at 13:20
  • i have not tried anything because i am totally blank. The numeric values may be in the starting or ending of the input. Commented Aug 31, 2012 at 13:21

16 Answers 16

23

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));
}
Sign up to request clarification or add additional context in comments.

2 Comments

yes, but the pattern is not fixed. i mean it's not always "d" after which the number will come.
@smya.dsh: I do not understand your latest comment. The \\d+ denotes one or more digit in regular expression language, it has nothing to do with the letter d (in this case at least).
14
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());
}

Comments

8

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

Comments

5

You could do something like:

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

Comments

2

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.

1 Comment

This will only work for this specific string: abc d 1234567890pqr 54897
2

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
}

Comments

2

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

Comments

2
        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.

1 Comment

Very simple of way of extracting numbers out of a long alphanumeric string.
2

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(" +");

4 Comments

Doesn't String nums = input.replaceAll("[0-9 ]", "") discard only digits?
@fade2black there’s a space character there in the character class too, between the 9 and the ], but thanks for the msg: I just noticed I was missing the negation ^. The code should work now.
my argument is that you remove all digits from the original string. You have just edited by adding '^'. Your previous regexp was wrong. It removed all digits and spaces while the OP asks the opposite.
@fade yes, and now I have fixed my error, so thanks for bringing this to my attention.
1

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.

2 Comments

your suggestion with the spaces would fail in the example at 1234567890pqr
@JonasEicher I thought it was 1234567890 pqr, not 1234567890pqr.
1
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);
    }
}

Comments

1

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

Comments

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

  }

 }

1 Comment

That will create one giant number, not keep them separate
0
 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

Comments

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

The result will be "1234567890 54897".

Comments

0
String str = "abc34bfg 56tyu";

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

output: 3456

1 Comment

You only added the parseInt-part which does not make the former answers less correct.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.