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?
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?
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).
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
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());
}
}
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);
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
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]);
}
We can simply use regular expression to extract the integer value from string
String str= "HEll1oTe45st23";
String intValue = str.replaceAll("[^0-9]", "");
System.out.print(Integer.parseInt(intValue));
Here, you can replaceAll string values with empty values and then parse the string to integer value. Further, you can use integer values.
Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...
Check this, List<String> list = new ArrayList<String>(); for (int i = 0; i < 10000; i++) { String value = (""+UUID.randomUUID().getLeastSignificantBits()).substring(3, ...
I am in the middle of solving a problem where I think it s best suited for a decorator and a state pattern. The high level setting is something like a sandwich maker and dispenser, where I have a set ...
I have been trying to execute a MS SQL Server stored procedure via JDBC today and have been unsuccessful thus far. The stored procedure has 1 input and 1 output parameter. With every combination I ...
I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...
If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...
I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....
I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...