Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.41 KB | None | 0 0
  1. import java.util.List;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4.  
  5. import static java.util.Arrays.asList;
  6.  
  7. public class Regex2 {
  8.     private static final String PHONE_REGEX = "(?:\\d{1,2} )?\\(?(\\d{3})\\)?([ -]?(\\d{3,4}))+";
  9.  
  10.     public static void main(String[] args) {
  11.         Regex2 regex = new Regex2();
  12.         regex.shouldMatchPhoneRegex();
  13.     }
  14.    
  15.     private void shouldMatchPhoneRegex() {
  16.         List<String> shouldMatch = asList("415-555-1234", "650-555-2345", "(416)555-3456", "202 555 4567", "4035555678", "1 416 555 9292");
  17.         List<String> captureGroups = asList("415", "650", "416", "202", "403", "416");
  18.  
  19.         shouldMatchRegexAndCaptures(PHONE_REGEX, shouldMatch, captureGroups);
  20.     }
  21.  
  22.     private void shouldMatchRegexAndCaptures(String regex, List<String> shouldMatch, List<String> captureGroups) {
  23.         for (int i = 0; i < shouldMatch.size(); i++) {
  24.             Pattern pattern = Pattern.compile(regex);
  25.             Matcher matcher = pattern.matcher(shouldMatch.get(i));
  26.             if (!matcher.matches()) {
  27.                 throw new IllegalStateException(shouldMatch.get(i) + " - Should match regex!");
  28.             }
  29.             if (!matcher.group(1).equals(captureGroups.get(i))) {
  30.                 throw new IllegalStateException(shouldMatch.get(i) + " - Should match - " + captureGroups.get(i) + " - capture group!");
  31.             }
  32.         }
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement