Friday, November 12, 2010

Java : Phone number validation using regular expression


package com.lnn.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PhoneNumberValidation {
      private static final Pattern PhoneNumberPattern = Pattern.compile("[0-9]{3}[-]{0,1}[0-9]{4}");

      public static boolean isValidPhoneNumber(String phone) {
            Matcher matcher = PhoneNumberPattern.matcher(phone);
            return matcher.matches();
      }
     
      public static void main(String[] args) {
            System.out.println(isValidPhoneNumber("123-4567"));
            System.out.println(isValidPhoneNumber("1234567"));
      }
}

No comments:

Post a Comment