Java 程序 - 使用字符串和正则表达式验证电子邮件地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16524107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Program - Email address verification using Strings and RegEx
提问by user2377778
The problem statement goes like this:
问题陈述是这样的:
We need to create a String data type called emailId
我们需要创建一个名为emailId的 String 数据类型
The email ID has to be set using appropriate setter methods.
必须使用适当的 setter 方法设置电子邮件 ID。
The validation rules for the email ID check have to be implemented in the main().
电子邮件 ID 检查的验证规则必须在 main() 中实现。
Conditions are:
条件是:
Overall length of the email ID must be >3 and <20.
The emailId must include "@" followed by a minimum of 1 and maximum of 2 "." characters.
The substring before "@" must contain a combination of Upper Case, Lower Case and "_"(underscore) symbols.
The first letter of the email Id must be in Upper Case.
电子邮件 ID 的总长度必须大于 3 且小于 20。
emailId 必须包含“@”,后跟最少 1 和最多 2 个“。” 人物。
“@”之前的子字符串必须包含大写、小写和“_”(下划线)符号的组合。
电子邮件 ID 的第一个字母必须大写。
If all the above conditions are valid, it should display "Email ID is valid" or else, it should display an appropriate error message
如果上述所有条件都有效,则应显示“电子邮件 ID 有效”,否则应显示相应的错误消息
This is my code:
这是我的代码:
public class EmailCheck {
String emailId;
public void setEmailId(String emailId){
this.emailId=emailId;
}
public String getEmailId(){
return emailId;
}
public static void main(String[] args) {
EmailCheck em = new EmailCheck();
em.setEmailId("[email protected]");
String email = em.getEmailId();
int length = email.length();
boolean flag1 = false;
boolean flag2 = false;
boolean flag3 = false;
boolean flag4 = false;
boolean flag5 = false;
boolean flag6 = false;
boolean flag7 = false;
int count = 0;
//Condition 1
if((length>3 && length<20)== true)
flag1 = true;
else
flag1 = false;
//Condition 2
int temp = email.length();
if(email.contains("@")){
flag2=true;
int a=email.indexOf("@");
for(int i=a;i<temp;i++){
if(email.charAt(i)=='.'){
flag3=true;
count=count+1;
}
}
if(count<1||count>2){
flag4=false;
}
else{
flag4=true;
}
}
else{
flag2 =false;
System.out.println("No @ symbol present");
}
//Condition 3
if(email.matches("[A-Z a-z _]+@.*")) //Unable to get the right RegEx here!
flag5 = true;
else
flag5 = false;
//Condition4
if(Character.isUpperCase(email.charAt(0))==true)
flag6 = true;
else
flag6=false;
if(flag1==true && flag2==true && flag3==true && flag4==true && flag5==true &&flag6==true)
System.out.println("Email ID is valid");
else{
if(flag1==false)
System.out.println("Inavlid length of Email ID");
if(flag2==false||flag3==false||flag4==false)
System.out.println("Invalid Position of Special Characters");
if(flag5==false)
System.out.println("Invalid combination for username");
if(flag6==false)
System.out.println("Invalid case of first letter");
}
}
}
I'm not sure of the condition #2(the logic?) and condition #3(the RegExp part). A few of the test cases seem correct, the rest of them are wrong(owing to faulty logic in #2 and esp #3, I think.)
我不确定条件#2(逻辑?)和条件#3(RegExp 部分)。一些测试用例似乎是正确的,其余的都是错误的(我认为是由于 #2 和 esp #3 中的错误逻辑。)
Please, tell me what changes have to be done here to get the right output. Thanks!
请告诉我必须在此处进行哪些更改才能获得正确的输出。谢谢!
采纳答案by rcbevans
If you insist on using regex you can use this but without validating properly you could be in for all kinds of trouble
如果您坚持使用正则表达式,您可以使用它,但如果没有正确验证,您可能会遇到各种麻烦
static Pattern emailPattern = Pattern.compile("[a-zA-Z0-9[!#$%&'()*+,/\-_\.\"]]+@[a-zA-Z0-9[!#$%&'()*+,/\-_\"]]+\.[a-zA-Z0-9[!#$%&'()*+,/\-_\"\.]]+");
public static boolean isValidEmail(String email) {
Matcher m = emailPattern.matcher(email); return !m.matches();
}
Or alternatively you could use
或者你可以使用
public static boolean isValidEmailAddress(String email) {
boolean result = true;
try {
InternetAddress emailAddr = new InternetAddress(email);
emailAddr.validate();
} catch (AddressException ex) {
result = false;
}
return result;
}
Which is a core java utility which would be better...
哪个是核心java实用程序会更好......
Note that neither of these will guarentee an address is actually valid, just that it is correctly formed and so hypothetically could exist
请注意,这些都不能保证地址实际上是有效的,只是它的格式正确,因此假设可能存在
String email_regex = "[A-Z]+[a-zA-Z_]+@\b([a-zA-Z]+.){2}\b?.[a-zA-Z]+";
String testString = "[email protected]";
Boolean b = testString.matches(email_regex);
System.out.println("String: " + testString + " :Valid = " + b);
will check for the last three constraints which you can then combine with
将检查最后三个约束,然后您可以将其与
string.length()>3 && string.length()<20
回答by thegrinner
Overall length of the email ID must be >3 and <20.
电子邮件 ID 的总长度必须大于 3 且小于 20。
You have this part fine - a pair of length checks. Things to consider:
你有这部分很好 - 一对长度检查。需要考虑的事项:
- You don't need
if (condition == true)
, justif (condition)
. - If this fails, you can stop processing the email and just display the error. The same applies for all your other error conditions.
- 你不需要
if (condition == true)
,只要if (condition)
。 - 如果失败,您可以停止处理电子邮件并仅显示错误。这同样适用于所有其他错误情况。
The emailId must include "@" followed by a minimum of 1 and maximum of 2 "." characters.
emailId 必须包含“@”,后跟最少 1 和最多 2 个“。” 人物。
Check for the @ sign first and get the index. Once you have that, you can split the string. You can then split the substring on periods and count them - you want two or three.
首先检查@符号并获取索引。一旦你有了它,你就可以拆分字符串。然后您可以在句点上拆分子字符串并计算它们 - 您需要两个或三个。
There's probably a regex that would do this as well.
可能有一个正则表达式也可以做到这一点。
The substring before "@" must contain a combination of Upper Case, Lower Case and "_"(underscore) symbols.
“@”之前的子字符串必须包含大写、小写和“_”(下划线)符号的组合。
You can use this approachto ensure your regex must match each part. As it stands, I believe your regex will work if there are caps, lowercase, oran underscore instead of checking for all three.
您可以使用这种方法来确保您的正则表达式必须匹配每个部分。就目前而言,我相信如果有大写、小写或下划线,您的正则表达式将起作用,而不是检查所有三个。
The first letter of the email Id must be in Upper Case.
电子邮件 ID 的第一个字母必须大写。
Same comments as for the first part, drop the == true
and short circuit the method if it fails.
与第一部分相同的评论,== true
如果失败,则放弃并短路该方法。