Reputation: 133
I have problems with the regex. somehow the online regextester does not work with the pattern.
I would like to allow
[email protected]
and
[email protected];[email protected];[email protected]
so one without semicolon and multiple with semicolon between, but not on the end
what I have:
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
public EmailValidator() {
pattern = Pattern.compile(EMAIL_PATTERN);
}
public boolean valid(final String email) {
matcher = pattern.matcher(email);
return matcher.matches();
}
Upvotes: 1
Views: 1408
Reputation: 426
See if this one works for you:
@Test
public void testValidEmail(){
String regex =
"(([A-Za-z0-9_\\-\\.])+\\@([A-Za-z0-9_\\-\\.])+\\.([A-Za-z]{2,4}))(((;|,|; | ;| ; | , | ,){1}"
+"([A-Za-z0-9_\\-\\.])+\\@([A-Za-z0-9_\\-\\.])+\\.([A-Za-z]{2,4}))*)";
Boolean matches = Pattern.matches(regex, "[email protected];[email protected];[email protected]");
Assert.assertTrue(matches);
}
Upvotes: 1
Reputation: 627327
Just take the pattern in between the anchors as the single email matching subpattern, and use it to build the final pattern:
private static final String SINGLE_EMAIL_PATTERN = "[_A-Za-z0-9-+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";
private static final String EMAIL_PATTERN = "^" + SINGLE_EMAIL_PATTERN + "(?:;" + SINGLE_EMAIL_PATTERN + ")*$";
Your pattern will look like the one here.
^
- will assert the start of stringSINGLE_EMAIL_PATTERN
- will match 1 email(?:;<SINGLE_EMAIL_PATTERN>)*
- will match 0 or more sequences of:
;
- a ;
<SINGLE_EMAIL_PATTERN>
- a single email$
- will assert the end of string.Upvotes: 1