Java Regular Expression match phone number

Introduction

"\\d{4}-\\d{8}|\\d{4}-\\d{7}" has three parts:

\\d{4}-\\d{8}
|
\\d{4}-\\d{7}

| means or.

\\d means digits.

{4} means four times.


public class Main {
    public static void main(String[] argv) throws Exception {
        String phone = "1231-12345678";
        System.out.println(checkFixedPhone(phone));
        //from w ww  . j a v  a2s  . c om
        phone = "1231-1234567";
        System.out.println(checkFixedPhone(phone));
        
        phone = "123-1234567";
        System.out.println(checkFixedPhone(phone));
    }

    public static boolean checkFixedPhone(String phone) {
        if (phone.matches("\\d{4}-\\d{8}|\\d{4}-\\d{7}")) {
            return true;
        } else {
            return false;
        }
    }
}



PreviousNext

Related