Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.List;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- import static java.util.Arrays.asList;
- public class Regex2 {
- private static final String PHONE_REGEX = "(?:\\d{1,2} )?\\(?(\\d{3})\\)?([ -]?(\\d{3,4}))+";
- public static void main(String[] args) {
- Regex2 regex = new Regex2();
- regex.shouldMatchPhoneRegex();
- }
- private void shouldMatchPhoneRegex() {
- List<String> shouldMatch = asList("415-555-1234", "650-555-2345", "(416)555-3456", "202 555 4567", "4035555678", "1 416 555 9292");
- List<String> captureGroups = asList("415", "650", "416", "202", "403", "416");
- shouldMatchRegexAndCaptures(PHONE_REGEX, shouldMatch, captureGroups);
- }
- private void shouldMatchRegexAndCaptures(String regex, List<String> shouldMatch, List<String> captureGroups) {
- for (int i = 0; i < shouldMatch.size(); i++) {
- Pattern pattern = Pattern.compile(regex);
- Matcher matcher = pattern.matcher(shouldMatch.get(i));
- if (!matcher.matches()) {
- throw new IllegalStateException(shouldMatch.get(i) + " - Should match regex!");
- }
- if (!matcher.group(1).equals(captureGroups.get(i))) {
- throw new IllegalStateException(shouldMatch.get(i) + " - Should match - " + captureGroups.get(i) + " - capture group!");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement