可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
First of all, I know that using regex for email is not recommended but I gotta test this out.
I have this regex:
\\b[A-Z0-9._%-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b
In Java, I did this:
Pattern p = Pattern.compile(\"\\\\b[A-Z0-9._%-]+@[A-Z0-9.-]+\\\\.[A-Z]{2,4}\\\\b\");
Matcher m = p.matcher(\"foobar@gmail.com\");
if (m.find())
System.out.println(\"Correct!\");
However, the regex fails regardless of whether the email is wel-formed or not. A \"find and replace\" inside Eclipse works fine with the same regex.
Any idea?
Thanks,
回答1:
FWIW, here is the Java code we use to validate email addresses. The Regexp\'s are very similar:
public static final Pattern VALID_EMAIL_ADDRESS_REGEX =
Pattern.compile(\"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\\\.[A-Z]{2,6}$\", Pattern.CASE_INSENSITIVE);
public static boolean validate(String emailStr) {
Matcher matcher = VALID_EMAIL_ADDRESS_REGEX .matcher(emailStr);
return matcher.find();
}
Works fairly reliably.
回答2:
Here is RFC822 compliant regex adapted for Java:
Pattern ptr = Pattern.compile(\"(?:(?:\\\\r\\\\n)?[ \\\\t])*(?:(?:(?:[^()<>@,;:\\\\\\\\\\\".\\\\[\\\\] \\\\000-\\\\031]+(?:(?:(?:\\\\r\\\\n)?[ \\\\t])+|\\\\Z|(?=[\\\\[\\\"()<>@,;:\\\\\\\\\\\".\\\\[\\\\]]))|\\\"(?:[^\\\\\\\"\\\\r\\\\\\\\]|\\\\\\\\.|(?:(?:\\\\r\\\\n)?[ \\\\t]))*\\\"(?:(?:\\\\r\\\\n)?[ \\\\t])*)(?:\\\\.(?:(?:\\\\r\\\\n)?[ \\\\t])*(?:[^()<>@,;:\\\\\\\\\\\".\\\\[\\\\] \\\\000-\\\\031]+(?:(?:(?:\\\\r\\\\n)?[ \\\\t])+|\\\\Z|(?=[\\\\[\\\"()<>@,;:\\\\\\\\\\\".\\\\[\\\\]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r\\\\n)?[ \\\\t])*)(?:\\\\.(?:(?:\\\\r\\\\n)?[ \\\\t])*(?:[^()<>@,;:\\\\\\\\\\\".\\\\[\\\\] \\\\000-\\\\031]+(?:(?:(?:\\\\r\\\\n)?[ \\\\t])+|\\\\Z|(?=[\\\\[\\\"()<>@,;:\\\\\\\\\\\".\\\\[\\\\]]))|\\\\[([^\\\\[\\\\]\\\\r\\\\\\\\]|\\\\\\\\.)*\\\\](?:(?:\\\\r\\\\n)?[ \\\\t])*))*\\\\>(?:(?:\\\\r\\\\n)?[ \\\\t])*))*)?;\\\\s*)\");
String[] emails = { \"\\\"Fred Bloggs\\\"@example.com\", \"user@.invalid.com\", \"Chuck Norris <gmail@chucknorris.com>\", \"webmaster@müller.de\", \"matteo@78.47.122.114\" };
for (String email : emails) {
System.out.println(email + \" is \" + (ptr.matcher(email).matches() ? \"valid\" : \"invalid\"));
}
Output:
\"Fred Bloggs\"@example.com is valid
user@.invalid.com is invalid
Chuck Norris <gmail@chucknorris.com> is valid
webmaster@müller.de is valid
matteo@78.47.122.114 is valid
The regex is taken from this post: Mail::RFC822::Address: regexp-based address validation. The results should coincide with online version.
回答3:
Don\'t. You will never end up with a valid expression.
For example these are all valid email addresses:
\"Abc\\@def\"@example.com
\"Fred Bloggs\"@example.com
\"Joe\\\\Blow\"@example.com
\"Abc@def\"@example.com
customer/department=shipping@examp le.com
$A12345@example.com
!def!xyz%abc@example.com
_somename@example.com
matteo(this is a comment).corti@example.com
root@[127.0.0.1]
Just to mention a few problems:
- you don\'t consider the many forms of specifying a host (e.g, by the IP address)
- you miss valid characters
- you miss non ASCII domain names
Before even beginning check the corresponding RFCs
回答4:
That\'s because you are forgetting case insensitivity :
Pattern regex = Pattern.compile(\"\\\\b[\\\\w.%-]+@[-.\\\\w]+\\\\.[A-Za-z]{2,4}\\\\b\");
This matches your example, although it ignores many valid e-mails.
回答5:
One another simple alternative to validate 99% of emails
public static final String EMAIL_VERIFICATION = \"^([\\\\w-\\\\.]+){1,64}@([\\\\w&&[^_]]+){2,255}.[a-z]{2,}$\";
回答6:
Is maching set to CASE_INSENSITIVE?
回答7:
You can use this method for validating email address in java.
public class EmailValidator {
private Pattern pattern;
private Matcher matcher;
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);
}
/**
* Validate hex with regular expression
*
* @param hex
* hex for validation
* @return true valid hex, false invalid hex
*/
public boolean validate(final String hex) {
matcher = pattern.matcher(hex);
return matcher.matches();
}
}
回答8:
General Email format (RE) which include also domain like co.in, co.uk, com, outlook.com etc.
And rule says that :
- Uppercase and lowercase English letters (a-z, A-Z)
- Digits 0 to 9
- Characters ! # $ % & \' * + - / = ? ^ _ ` { | } ~ Character.
(dot, period, full stop) provided that it is not the first or last
character, and provided also that it does not appear two or more
times consecutively.
[a-zA-Z0-9]+[._a-zA-Z0-9!#$%&\'*+-/=?^_`{|}~]*[a-zA-Z]*@[a-zA-Z0-9]{2,8}.[a-zA-Z.]{2,6}
回答9:
This is a valid regex for validating e-mails. It\'s totally compliant with RFC822 and accepts IP address and server names (for intranet purposes).
public static boolean isEmailValid(String email) {
final Pattern EMAIL_REGEX = Pattern.compile(\"[a-z0-9!#$%&\'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&\'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\", Pattern.CASE_INSENSITIVE);
return EMAIL_REGEX.matcher(email).matches();
}
Here are some output examples, when you call isEmailValid(emailVariable)
:
john@somewhere.com // valid
john.foo@somewhere.com // valid
john.foo+label@somewhere.com // valid (with +label - Gmail accepts it!)
john@192.168.1.10 // valid (with IP addresses)
john+label@192.168.1.10 // valid (with +label and IP address)
john.foo@someserver // valid (with no first domain level)
JOHN.FOO@somewhere.com // valid (case insensitive)
@someserver // invalid
@someserver.com // invalid
john@. // invalid
.@somewhere.com // invalid
回答10:
Regex : ^[\\\\w!#$%&’*+/=?
{|}~^-]+(?:\\.[\\w!#$%&’*+/=?{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\\\.)+[a-zA-Z]{2,6}$
public static boolean isValidEmailId(String email) {
String emailPattern = \"^[\\\\w!#$%&’*+/=?`{|}~^-]+(?:\\\\.[\\\\w!#$%&’*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\\\.)+[a-zA-Z]{2,6}$\";
Pattern p = Pattern.compile(emailPattern);
Matcher m = p.matcher(email);
return m.matches();
}
回答11:
If you want to allow non-latain characters, this one works quite well for me.
\"^[\\\\p{L}\\\\p{N}\\\\._%+-]+@[\\\\p{L}\\\\p{N}\\\\.\\\\-]+\\\\.[\\\\p{L}]{2,}$\"
It does not allow IP\'s after the @ but most valid email in the from of xxx@xxx.TDL
could be validated with it.
\\p{L}
validates UTF-Letters and \\p{N}
validates UTF-Numbers. You can check this doc for more information.
回答12:
Try the below code for email is format of
jsmith@example.com
1st part -jsmith
2nd part -@example.com
1. In the 1 part it will allow 0-9,A-Z,dot sign(.),underscore sign(_)
2. In the 2 part it will allow A-Z, must be @ and .
^[a-zA-Z0-9_.]+@[a-zA-Z.]+?\\.[a-zA-Z]{2,3}$
回答13:
I have tested this below regular expression
for single and multiple consecutive dots in domain
name -
([A-Za-z0-9-_.]+@[A-Za-z0-9-_]+(?:\\.[A-Za-z0-9]+)+)
and here are the examples which were completely fulfilled by above regex
.
End_user@live.com
End.u@exm-tech.net
enduser9876@gmail.in
end_user@mywebsite.ac.in.gui
Another984.User2@mail.edu.sg
Another987_User5@mail.show.au
Slow_User@example_domain.au.in
iamthemostsimpleremailhere@example.com
I have tried to cover maximum commonly used email id\'s validation
by this above illustrated regex
and yet working...
If you still know some consequentially used email id\'s
had left here, please let me know in comment section!
回答14:
String emailRegex = \"[a-zA-Z0-9_.]+@[a-zA-Z0-9]+.[a-zA-Z]{2,3}[.] {0,1}[a-zA-Z]+\";
Pattern.matches(emailRegex,\"You_Input_Mail_Id\");
This is the regex to match valid email addresses.
回答15:
you can use a simple regular expression for validating email id,
public boolean validateEmail(String email){
return Pattern.matches(\"[_a-zA-Z1-9]+(\\\\.[A-Za-z0-9]*)*@[A-Za-z0-9]+\\\\.[A-Za-z0-9]+(\\\\.[A-Za-z0-9]*)*\", email)
}
Description :
- [_a-zA-Z1-9]+ - it will accept all A-Z,a-z, 0-9 and _ (+ mean it must be occur)
- (\\.[A-Za-z0-9]) - it\'s optional which will accept . and A-Z, a-z, 0-9( * mean its optional)
- @[A-Za-z0-9]+ - it wil accept @ and A-Z,a-z,0-9
- \\.[A-Za-z0-9]+ - its for . and A-Z,a-z,0-9
- (\\.[A-Za-z0-9]) - it occur, . but its optional
回答16:
Regex for Facebook-like validation:
public static final String REGEX_EMAIL_VALIDATION = \"^[\\\\w-\\\\+]+(\\\\.[\\\\w]+)*@[\\\\w-]+(\\\\.[\\\\w]+)*(\\\\.[a-zA-Z]{2,})$\";
Dto for Unit tests(with Lombok):
@Data
@Accessors(chain = true)
@FieldDefaults(level = AccessLevel.PRIVATE)
public class UserCreateDto {
@NotNull
@Pattern(regexp = REGEX_EMAIL_VALIDATION)
@Size(min = 1, max = 254)
String email;
}
Valid/invalid emails below with Unit tests:
public class UserCreateValidationDtoTest {
private static final String[] VALID_EMAILS = new String[]{\"email@yahoo.com\", \"email-100@yahoo.com\",
\"Email.100@yahoo.com\", \"email111@email.com\", \"email-100@email.net\",
\"email.100@email.com.au\", \"emAil@1.com\", \"email@gmail.com.com\",
\"email+100@gmail.com\", \"emAil-100@yahoo-test.com\", \"email_100@yahoo-test.ABC.CoM\"};
private static final String[] INVALID_EMAILS = new String[]{\"あいうえお@example.com\", \"email@111\",
\"email\", \"email@.com.my\", \"email123@gmail.\", \"email123@.com\", \"email123@.com.com\",
\".email@email.com\", \"email()*@gmAil.com\", \"eEmail()*@gmail.com\", \"email@%*.com\", \"email..2002@gmail.com\",
\"email.@gmail.com\", \"email@email@gmail.com\", \"email@gmail.com.\"};
private Validator validator;
@Before
public void setUp() throws Exception {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
@Test
public void emailValidationShouldBeValid() throws Exception {
Arrays.stream(VALID_EMAILS)
.forEach(email -> {
Set<ConstraintViolation<UserCreateDto>> violations = validateEmail(
new UserCreateDto().setEmail(email));
System.out.println(\"Email: \" + email + \", violations: \" + violations);
Assert.assertTrue(violations.isEmpty());
}
);
}
@Test
public void emailValidationShouldBeNotValid() throws Exception {
Arrays.stream(INVALID_EMAILS)
.forEach(email -> {
Set<ConstraintViolation<UserCreateDto>> violations = validateEmail(
new UserCreateDto().setEmail(email));
System.out.println(\"Email: \" + email + \", violations: \" + violations);
Assert.assertTrue(!violations.isEmpty());
}
);
}
private Set<ConstraintViolation<UserCreateDto>> validateEmail(UserCreateDto user) {
String emailFieldName = \"email\";
return validator.validateProperty(user, emailFieldName);
}
}