验证手机号码android

Nik*_*las 0 java android

我试图弄清楚这个验证我的 Android 电话号码的工作原理。

我已添加代码并希望验证 46123456789,但最后一个数字 (9) 并未添加到电话号码中。

我用这个:

/**
     * @param phone
     * @return The number which satisfies the above criteria, is a valid mobile Number.
     * The first digit should contain number between 0 to 9.
     * The rest 9 digit can contain any number between 0 to 9.
     * The mobile number can have 11 digits also by including 0 at the starting.
     * The mobile number can be of 12 digits also by including 46 at the starting
     */
    public static boolean isValidPhoneNumber(String phone) {
        phone = trimPhoneNumber(phone);
        // The given argument to compile() method
        // is regular expression. With the help of
        // regular expression we can validate mobile
        // number.
        // 1) Begins with 0 or 46
        // 2) Then contains 6 or 7 or 8 or 9.
        // 3) Then contains 9 digits
        Pattern p = Pattern.compile("(0/46)?[0-9][0-10]{9}");

        // Pattern class contains matcher() method
        // to find matching between given number
        // and regular expression
        Matcher m = p.matcher(phone);
        return (m.find() && m.group().equals(phone));
    }

    public static String trimPhoneNumber(String phone) {
        if (TextUtils.isEmpty(phone)) {
            return phone;
        } else {
            try {
                phone = phone.replace("+46", "");
                phone = phone.replaceAll("[^0-9]", "");//replace all except 0-9
                return phone;
            } catch (Exception e) {
                e.printStackTrace();
                return phone;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

我错过了什么吗

HFZ*_*HFZ 5

使用这个模式:

^\s*(?:(?:\+?46)|0)(?:\d){9,10}\s*$
Run Code Online (Sandbox Code Playgroud)

^在开始和$结束时确保模式与整个输入匹配

\s*修剪任何空格或制表符 \d捕获任何数字

(?:\d){9,10}表示该模式(?:\d)应重复 9 至 10 次。

`` 模式以 (+4646) 开头或0后跟 9 或 10 位数。

如果它可以包含-数字或数字之间有空格,请使用:

^\s*(?:(?:\+?46)|0)(?:[- ]*\d){9,10}\s*$
Run Code Online (Sandbox Code Playgroud)

你可以在这里测试正则表达式