Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract numbers from an alpha numeric string using android

I have to extract only numeric values from String str="sdfvsdf68fsdfsf8999fsdf09". How can I extract numbers from an alpha numeric string in android?

like image 253
Prasanth_AndroidJD Avatar asked May 24 '12 09:05

Prasanth_AndroidJD


People also ask

How do I retrieve numbers from a string?

The number from a string in javascript can be extracted into an array of numbers by using the match method. This function takes a regular expression as an argument and extracts the number from the string. Regular expression for extracting a number is (/(\d+)/).

How do I extract all digits from a string?

This problem can be solved by using split function to convert string to list and then the list comprehension which can help us iterating through the list and isdigit function helps to get the digit out of a string.


3 Answers

String str="sdfvsdf68fsdfsf8999fsdf09";
String numberOnly= str.replaceAll("[^0-9]", "");

update:

String str="fgdfg12°59'50\" Nfr | gdfg: 80°15'25\" Efgd";
String[] spitStr= str.split("\\|");

String numberOne= spitStr[0].replaceAll("[^0-9]", "");
String numberSecond= spitStr[1].replaceAll("[^0-9]", "");
like image 73
Mohammed Azharuddin Shaikh Avatar answered Nov 16 '22 03:11

Mohammed Azharuddin Shaikh


public static String getOnlyNumerics(String str) {

    if (str == null) {
        return null;
    }

    StringBuffer strBuff = new StringBuffer();
    char c;

    for (int i = 0; i < str.length() ; i++) {
        c = str.charAt(i);

        if (Character.isDigit(c)) {
            strBuff.append(c);
        }
    }
    return strBuff.toString();
}
like image 22
Vinay Kumar Baghel Avatar answered Nov 16 '22 04:11

Vinay Kumar Baghel


public static int extractNumberFromAnyAlphaNumeric(String alphaNumeric) {
    alphaNumeric = alphaNumeric.length() > 0 ? alphaNumeric.replaceAll("\\D+", "") : "";
    int num = alphaNumeric.length() > 0 ? Integer.parseInt(alphaNumeric) : 0; // or -1 
    return num;
}

You can set the value to 0 or -1 (what to do if no number is found in the alphanumeric at all) as per your needs

like image 1
Sean Das Avatar answered Nov 16 '22 03:11

Sean Das