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\
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 believe you can do something like:
Scanner in = new Scanner("Hello123").useDelimiter("[^0-9]+");
int integer = in.nextInt();
EDIT: Added useDelimiter suggestion by Carlos
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
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());
}
}
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);
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]);
}