题解 | #邮箱验证#
邮箱验证
https://www.nowcoder.com/practice/8f908eeee4aa412ca88304f0acbaa1f9
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str = scanner.next(); String emailMatcher = "[a-zA-Z0-9]+@[a-zA-Z0-9]+\\.[a-zA-Z0-9]+"; //write your code here...... int index1 = 0; int index2 = 0; String pastOne = ""; String pastTwo = ""; String pastThree = ""; try { //第一部分字串 index1 = str.indexOf("@"); pastOne = str.substring(0, index1); //第二部分字串 index2 = str.indexOf("."); pastTwo = str.substring(index1 + 1, index2); //第三部分字串 pastThree = str.substring(index2 + 1, str.length()); //第三部分的字串长度 int index3 = pastThree.length() - index2 - 1; //第二部分的字串长度 index2 -= (index1 + 1); //利用方法进行判断格式是否合法 if (method(pastOne, index1) && method(pastTwo, index2) && method(pastThree, index3)) { System.out.println("邮箱格式合法"); } else { System.out.println("邮箱格式不合法"); } } catch (Exception e) { System.out.println("邮箱格式不合法"); } } public static boolean method(String str, int index) { boolean legal = true; for (int i = 0; i < index; i++) { //如果邮箱格式合法则不改变legal的值 if ((str.charAt(i) >= '0') && (str.charAt(i) <= '9') ) { } else if (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') { } else if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') { } else { //不合法 legal = false; } } if (index == 0) { return false; } return legal; } }