Suppose I have a String which begins with a number. How can I get/extract all the first numbers and convert them to an Integer? Don't want all the numbers on the String, I want the numbers since the first one until the last one before any other letter or character.
For example:
String s= "5634-abofrda/+l8908"; // 5634
String str="78695t08675jgk"; // 78695
How do I get the number 5634? I'm looking for a general solution, not specific for the cases decribed.
This method can be used to return a number before another character is found
static int getNumbers(String s) {
String[] n = s.split(""); //array of strings
StringBuffer f = new StringBuffer(); // buffer to store numbers
for (int i = 0; i < n.length; i++) {
if((n[i].matches("[0-9]+"))) {// validating numbers
f.append(n[i]); //appending
}else {
//parsing to int and returning value
return Integer.parseInt(f.toString());
}
}
return 0;
}
Usage:
getNumbers(s);
getNumbers(str);
Output:
5634
78695
Use a regular expression. Match and group digits followed by anything and replace everything with the matched group. Like,
System.out.println(s.replaceAll("(\\d+).+", "$1"));
Prints (as requested)
5634
The simplest option might be to just use String#split
:
String s = "5634-abofrda/+l8908";
String nums = s.split("-")[0];
Note that in the case that a hyphen should not appear in the input string, then nums
would just be the entire string.
Or perhaps you want this:
String s = "5634-abofrda/+l8908";
String nums = s.split("(?=\\D)")[0];
The lookahead (?=\D)
will split the string everytime there is a non digit character. This would leave the leading digits in the first string of the split array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With