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?


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.


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


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


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

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