我正在尝试编写一个小程序,要求用户输入电子邮件地址.然后,我验证其是否为有效的电子邮件地址.像"example@example"一样有效,但"example @@ example"则无效.
I'm trying to write a little program where I ask the user to enter an email address. And then I verify if its a valid email address or not. Like "example@example" would be valid, but "example@@example" would be invalid.
这是我的代码,我可以通过它来检测是否有@和.字符,但我需要确保它只出现一次,并且@出现在点(.)之前
Here's my code, I have made it work to detect if there is an @ and . character in there, but I need to make sure it only appears once, and that the @ appears before the dot (.)
import java.util.Scanner; public class email { public static void main(String args[]) { Scanner skanni = new Scanner(System.in); System.out.println("Sládu inn email adressuna thína."); System.out.println("Email: "); String mail = skanni.nextLine(); boolean b1=mail.contains("@") && mail.contains("."); if (b1) { System.out.println("This email is valid"); }else{ System.out.println("this email is invalid"); } } }如果有人可以提供帮助,将不胜感激!
If anyone could help, it would be greatly appreciated!
谢谢大家的回答和帮助.如果将来有人会做类似的事情,我将在下面发布最终代码.哦,您可以忽略该评论.您可能不会理解:)
Thanks everyone for your answers and help. I'm posting the final code below if anyone else will be doing something similar in the future. Oh and you can ignore the comment. You probably won't understand it :)
import java.util.Scanner; import java.util.regex.*; public class email { public static void main(String args[]) { Scanner skanni = new Scanner(System.in); System.out.println("Sládu inn email adressuna thína."); System.out.println("Email: "); String mail = skanni.nextLine(); /*Skilgreining á eftirfarandi kóda * ^ táknid er byrjunin á strengnum * thad sem ég set innan sviga á eftir, er thad sem ég legg áherslu á í hverju sinni * [A-Za-z0-9] eru leyfilegir stafir í fyrsta lid emailsins, sbr: (birgir09)dæmi@gmail * + á milli táknar ad naesti svigi byrjar, thad er ad segja. (\\-[A-Za-z0-9-]) * *@ táknar ad @ merkid er á milli sviganna * "[A-Za-z0-9] er thad sem kemur fyrir framan punktinn sbr. (gmail) * (\\.[A-Za-z0-9]) er thad sem kemur fyrir aftan punkt sbr gmail.(com) */ Pattern p = Patternpile("^[A-Za-z0-9-]+(\\-[A-Za-z0-9])*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9])"); Matcher m = p.matcher(mail); if (m.find()) { System.out.println("Thetta email er loglegt."); }else{ System.out.println("Thetta email er ekki loglegt."); } } } 推荐答案这里有一个用于验证邮件地址的正则表达式:
Here you have a regex for validating mail addresses:
Java regex电子邮件
更多推荐
邮件地址验证JAVA
发布评论