|
| 1 | +/** |
| 2 | + * Algorithms-In-Java |
| 3 | + * RegexForUSPhoneNumber.java |
| 4 | + */ |
1 | 5 | package com.deepak.algorithms.Regex; |
2 | 6 |
|
3 | 7 | import java.util.regex.Matcher; |
4 | 8 | import java.util.regex.Pattern; |
5 | 9 |
|
| 10 | +/** |
| 11 | + * Regular expression for US Phone Numbers |
| 12 | + * |
| 13 | + * @author Deepak |
| 14 | + */ |
6 | 15 | public class RegexForUSPhoneNumber { |
7 | | - |
| 16 | + |
| 17 | + /** |
| 18 | + * Main method to test the program |
| 19 | + * |
| 20 | + * @param args |
| 21 | + */ |
8 | 22 | public static void main(String[] args) { |
9 | | - System.out.println(matchUSPhoneNumber("425-633-6014")); |
10 | | - System.out.println(matchUSPhoneNumber("425-633-601")); |
11 | | - System.out.println(matchUSPhoneNumber("425-6336014")); |
12 | | - System.out.println(matchUSPhoneNumber("(425)-633-6014")); |
13 | | - System.out.println(matchUSPhoneNumber("42-33-6014")); |
14 | | - System.out.println(matchUSPhoneNumber("-633-6014")); |
15 | | - System.out.println(matchUSPhoneNumber("6014")); |
16 | | - System.out.println(matchUSPhoneNumber("425-633-60145")); |
| 23 | + System.out.println(matchUSPhoneNumber("4256336014")); // true |
| 24 | + System.out.println(matchUSPhoneNumber(" 4256336014")); // false |
| 25 | + System.out.println(matchUSPhoneNumber("425-633-6014")); // true |
| 26 | + System.out.println(matchUSPhoneNumber("425-633-601")); // false |
| 27 | + System.out.println(matchUSPhoneNumber("425-6336014")); // true |
| 28 | + System.out.println(matchUSPhoneNumber("(425)-633-6014")); // true |
| 29 | + System.out.println(matchUSPhoneNumber("42-33-6014")); // false |
| 30 | + System.out.println(matchUSPhoneNumber("-633-6014")); // false |
| 31 | + System.out.println(matchUSPhoneNumber("6014")); // false |
| 32 | + System.out.println(matchUSPhoneNumber("425-633-60145")); // false |
17 | 33 | } |
18 | | - |
| 34 | + |
19 | 35 | /** |
20 | 36 | * Method to match US phone number |
| 37 | + * Explanation : |
| 38 | + * => Phone number can be in below format |
| 39 | + * 1. First part should have 3 digits |
| 40 | + * 2. Second part should have 3 digits |
| 41 | + * 3. Third part should have 4 digits |
| 42 | + * => Now, there could be various possibilities in between, |
| 43 | + * i.e we may have a -, a space, no white space or a braces () |
| 44 | + * |
| 45 | + * Explanation of Regular Expression : |
| 46 | + * |
| 47 | + * There will be 3 groups since I have 3 different blocks in my input. |
| 48 | + * For groups, we can use [0-9]{3} or [0-9]{4} |
| 49 | + * ^ - start of the string |
| 50 | + * $ - end of the string |
| 51 | + * \\ - matches the character literally |
| 52 | + * () - capture everything that is enclosed |
| 53 | + * ? Quantifier - matches between 0 and 1 times |
| 54 | + * [-.\\s] - Match anything out of these |
21 | 55 | * |
22 | 56 | * @param input |
23 | 57 | * @return {@link boolean} |
|
0 commit comments