Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the first numbers from a String on Java

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.

like image 492
eyelash Avatar asked Dec 30 '18 02:12

eyelash


3 Answers

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
like image 144
CristianoDeVinni Avatar answered Oct 09 '22 16:10

CristianoDeVinni


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
like image 25
Elliott Frisch Avatar answered Oct 09 '22 16:10

Elliott Frisch


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.

like image 40
Tim Biegeleisen Avatar answered Oct 09 '22 15:10

Tim Biegeleisen