private static void validatePhone () { //Validate phone no. String expression = "^\\d{3}-?\\d{3}-?\\d{4}$"; String str1 = "1233456789"; //It will match. String str2 = "2dF1"; //It wont match. String str3 = "a33345345"; //It wont match. Pattern pattern = Pattern.compile(expression); Matcher matcher = pattern.matcher(str1); boolean found = false; if (matcher.find()) { System.out.println (str1 + " - is valid phone no."); found = true; } if(!found){ System.out.println(str1 + " - is not a valid phone no."); } }
Sunday, July 10, 2011
Regular Expression - Validate phone no
Here is a simple program to validate phone no with nnn-nnn-nnnn/nnnnnnnnnn format
Labels:
Java