23

What is the best way to extract the integer part of a string like

Hello123

How do you get the 123 part. You can sort of hack it using Java's Scanner, is there a better way?

skaffman
  • 381,978
  • 94
  • 789
  • 754
Verhogen
  • 23,861
  • 32
  • 81
  • 109

8 Answers8

39

As explained before, try using Regular Expressions. This should help out:

String value = "Hello123";
String intValue = value.replaceAll("[^0-9]", ""); // returns 123

And then you just convert that to an int (or Integer) from there.

Slacker
  • 3
  • 3
Ascalonian
  • 13,595
  • 18
  • 66
  • 102
26

I believe you can do something like:

Scanner in = new Scanner("Hello123").useDelimiter("[^0-9]+");
int integer = in.nextInt();

EDIT: Added useDelimiter suggestion by Carlos

Brian Hasden
  • 3,940
  • 2
  • 26
  • 36
  • 1
    In what namespave can i find Scanner. – Paul Creasey Dec 14 '09 at 20:33
  • Yeah, it's not necessarily the sleekest or most elegant way to go, but it should work. It's even used in the scanner documentation at http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html – Brian Hasden Dec 14 '09 at 20:35
  • 2
    The documentation for `nextInt` states "This method will throw InputMismatchException if the next token cannot be translated into a valid int" which is the case for `Hello123`. Can use `in.useDelimiter("[^0-9]+");` to *ignore* non-digits – user85421 Dec 14 '09 at 20:57
  • Good point. Sorry about that. Missed the default delimiter stuff. That's what I get for not trying it out first. – Brian Hasden Dec 14 '09 at 21:00
11

Why don't you just use a Regular Expression to match the part of the string that you want?

[0-9]

That's all you need, plus whatever surrounding chars it requires.

Look at http://www.regular-expressions.info/tutorial.html to understand how Regular expressions work.

Edit: I'd like to say that Regex may be a little overboard for this example, if indeed the code that the other submitter posted works... but I'd still recommend learning Regex's in general, for they are very powerful, and will come in handy more than I'd like to admit (after waiting several years before giving them a shot).

Crowe T. Robot
  • 2,007
  • 17
  • 18
4

Assuming you want a trailing digit, this would work:

import java.util.regex.*;

public class Example {


    public static void main(String[] args) {
        Pattern regex = Pattern.compile("\\D*(\\d*)");
        String input = "Hello123";
        Matcher matcher = regex.matcher(input);

        if (matcher.matches() && matcher.groupCount() == 1) {
            String digitStr = matcher.group(1);
            Integer digit = Integer.parseInt(digitStr);
            System.out.println(digit);            
        }

        System.out.println("done.");
    }
}
Michael Easter
  • 21,462
  • 7
  • 70
  • 97
  • Well, it would work for your example and for "small" numbers. It will clearly fail for large numbers that won't fit into an int. – Michael Easter Dec 14 '09 at 21:47
4

I had been thinking Michael's regex was the simplest solution possible, but on second thought just "\d+" works if you use Matcher.find() instead of Matcher.matches():

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Example {

    public static void main(String[] args) {
        String input = "Hello123";
        int output = extractInt(input);

        System.out.println("input [" + input + "], output [" + output + "]");
    }

    //
    // Parses first group of consecutive digits found into an int.
    //
    public static int extractInt(String str) {
        Matcher matcher = Pattern.compile("\\d+").matcher(str);

        if (!matcher.find())
            throw new NumberFormatException("For input string [" + str + "]");

        return Integer.parseInt(matcher.group());
    }
}
ecto
  • 273
  • 1
  • 2
  • 11
4

Although I know that it's a 6 year old question, but I am posting an answer for those who want to avoid learning regex right now(which you should btw). This approach also gives the number in between the digits(for eg. HP123KT567 will return 123567)

    Scanner scan = new Scanner(new InputStreamReader(System.in));
    System.out.print("Enter alphaNumeric: ");
    String x = scan.next();
    String numStr = "";
    int num;

    for (int i = 0; i < x.length(); i++) {
        char charCheck = x.charAt(i);
        if(Character.isDigit(charCheck)) {
            numStr += charCheck;
        }
    }

    num = Integer.parseInt(numStr);
    System.out.println("The extracted number is: " + num);
hackrush
  • 88
  • 9
2

This worked for me perfectly.

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

OutPut:

1234
567
890
Muhammad Maqsood
  • 1,209
  • 14
  • 16
0
String[] parts = s.split("\\D+");    //s is string containing integers
int[] a;
a = new int[parts.length];
for(int i=0; i<parts.length; i++){
a[i]= Integer.parseInt(parts[i]);
System.out.println(a[i]);
}