Android之利用正则表达式校验邮箱、手机号、密码、身份证号码等

概述

现在Android应用在注册的时候基本会校验邮箱、手机号、密码、身份证号码其中一项或多项,特此收集了相关的正则表达式给大家分享。除了正则表达式,文章末尾提供Demo中有惊喜哦!

具体验证的图片效果就不做展示了,有需要可以下载Demo演示。下面就贴出校检类。

/**
* 校验器:利用正则表达式校验邮箱、手机号等
* @author Mr.duan
*/
public class Validator {
/**
* 正则表达式:验证用户名(不包含中文和特殊字符)如果用户名使用手机号码或邮箱 则结合手机号验证和邮箱验证
*/
public static final String REGEX_USERNAME = "^[a-zA-Z]\\w{5,17}$"; /**
* 正则表达式:验证密码(不包含特殊字符)
*/
public static final String REGEX_PASSWORD = "^[a-zA-Z0-9]{6,16}$"; /**
* 正则表达式:验证手机号
*/
public static final String REGEX_MOBILE = "^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$"; /**
* 正则表达式:验证邮箱
*/
public static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$"; /**
* 正则表达式:验证汉字(1-9个汉字) {1,9} 自定义区间
*/
public static final String REGEX_CHINESE = "^[\u4e00-\u9fa5]{1,9}$"; /**
* 正则表达式:验证身份证
*/
public static final String REGEX_ID_CARD = "(^\\d{15}$)|(^\\d{17}([0-9]|X)$)"; /**
* 正则表达式:验证URL
*/
public static final String REGEX_URL = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?"; /**
* 正则表达式:验证IP地址
*/
public static final String REGEX_IP_ADDR = "(2[5][0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})"; /**
* 校验用户名
* @param username
* @return 校验通过返回true,否则返回false
*/
public static boolean isUserName(String username) {
return Pattern.matches(REGEX_USERNAME, username);
} /**
* 校验密码
* @param password
* @return 校验通过返回true,否则返回false
*/
public static boolean isPassword(String password) {
return Pattern.matches(REGEX_PASSWORD, password);
} /**
* 校验手机号
* @param mobile
* @return 校验通过返回true,否则返回false
*/
public static boolean isMobile(String mobile) {
return Pattern.matches(REGEX_MOBILE, mobile);
} /**
* 校验邮箱
* @param email
* @return 校验通过返回true,否则返回false
*/
public static boolean isEmail(String email) {
return Pattern.matches(REGEX_EMAIL, email);
} /**
* 校验汉字
* @param chinese
* @return 校验通过返回true,否则返回false
*/
public static boolean isChinese(String chinese) {
return Pattern.matches(REGEX_CHINESE, chinese);
} /**
* 校验身份证
* @param idCard
* @return 校验通过返回true,否则返回false
*/
public static boolean isIDCard(String idCard) {
return Pattern.matches(REGEX_ID_CARD, idCard);
} /**
* 校验URL
* @param url
* @return 校验通过返回true,否则返回false
*/
public static boolean isUrl(String url) {
return Pattern.matches(REGEX_URL, url);
} /**
* 校验IP地址
* @param ipAddress
* @return
*/
public static boolean isIPAddress(String ipAddress) {
return Pattern.matches(REGEX_IP_ADDR, ipAddress);
} }

后记 
感谢玩Android 3群的小伙伴的建议,Demo为最初始版本(上传后的资源不能再操作),Validator 类代码请以博文贴出的代码为准,会对常用的验证做出更新,有新的建议可以给我留言哦~

上源码

上一篇:hdoj:2033


下一篇:【JavaScript OPP基础】---新手必备