get Only Digits From String - Android java.util.regex

Android examples for java.util.regex:Digit Pattern

Description

get Only Digits From String

Demo Code


public class Main{

    /**//w  w w.  ja  v  a 2  s . c  o m
     * get only digits from your string
     *
     * @param stringWithDigits
     *          string you want to get digits from, can be null or empty or even without digits
     * @return String with only digits from stringWithDigits or empty string "" if stringWithDigits was null or did not contain any digits.
     *          Example: stringWithDigits = "afb1et2fnvf3fs4", result = "1234"
     */
    public static String getOnlyDigitsFromString(String stringWithDigits) {
        return isNullOrEmpty(stringWithDigits) ? "" : stringWithDigits
                .replaceAll("\\D", "");
    }

    /**
     * Checks is string null or its length == 0, very useful
     *
     * @param string
     *          object to check, can be null :D
     * @return {@code true} if string is null or its length == 0, {@code false} otherwise
     */
    public static boolean isNullOrEmpty(String string) {
        return string == null || string.length() == 0;
    }
}

Related Tutorials