Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.58 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 Regex3 {
  8.     private static final String EMAIL_REGEX = "(\\w+\\.\\w+|\\w+)(\\+\\w+)?@hogwarts(\\.\\w{2,3})+";
  9.  
  10.     public static void main(String[] args) {
  11.         Regex3 regex = new Regex3();
  12.         regex.shouldMatchEmailRegex();
  13.     }
  14.  
  15.     private void shouldMatchEmailRegex() {
  16.         List<String> shouldMatch = asList("tom@hogwarts.com", "tom.riddle@hogwarts.com",
  17.                 "tom.riddle+regexone@hogwarts.com", "tom@hogwarts.eu.com", "potter@hogwarts.com", "harry@hogwarts.com",
  18.                 "hermione+regexone@hogwarts.com");
  19.         List<String> captureGroups = asList("tom", "tom.riddle", "tom.riddle", "tom", "potter", "harry", "hermione");
  20.  
  21.         shouldMatchRegexAndCaptures(EMAIL_REGEX, shouldMatch, captureGroups);
  22.     }
  23.  
  24.     private void shouldMatchRegexAndCaptures(String regex, List<String> shouldMatch, List<String> captureGroups) {
  25.         for (int i = 0; i < shouldMatch.size(); i++) {
  26.             Pattern pattern = Pattern.compile(regex);
  27.             Matcher matcher = pattern.matcher(shouldMatch.get(i));
  28.             if (!matcher.matches()) {
  29.                 throw new IllegalStateException(shouldMatch.get(i) + " - Should match regex!");
  30.             }
  31.             if (!matcher.group(1).equals(captureGroups.get(i))) {
  32.                 throw new IllegalStateException(
  33.                         shouldMatch.get(i) + " - Should match - " + captureGroups.get(i) + " - capture group!");
  34.             }
  35.         }
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement