Java无需正则实现邮箱格式校验方法的问题咨询
实现代码
public static boolean emailAddress(String str) { // 处理空入参避免空指针异常 if (str == null) { return false; } // 规则1:不能包含空格 if (str.contains(" ")) { return false; } // 规则1:只能存在1个@符号 int firstAt = str.indexOf('@'); int lastAt = str.lastIndexOf('@'); if (firstAt != lastAt || firstAt == -1) { return false; } // 校验最后一个.必须在@之后 int lastDot = str.lastIndexOf('.'); if (lastDot <= firstAt) { return false; } // 规则2:校验@前字符数>2 if (firstAt <= 2) { return false; } // 规则2:校验@与最后一个.之间的字符数>2 int betweenLength = lastDot - firstAt - 1; if (betweenLength <= 2) { return false; } // 规则2:校验.之后的字符数>2 int afterDotLength = str.length() - lastDot - 1; if (afterDotLength <= 2) { return false; } // 所有校验通过 return true; }
逻辑说明
完全不需要用到正则,仅通过JDK自带的字符串索引查询方法即可实现全部校验:
- 用
indexOf和lastIndexOf查询@的位置,二者返回值不同就说明存在至少2个@ - 索引数值本身就等于对应位置前面的字符总数,不需要额外遍历计数
- 所有边界场景(比如@在开头、.在结尾、.在@前面等)都会被长度校验自动拦截
内容的提问来源于stack exchange,提问作者brmk
相关产品推荐
相关产品推荐

