package com.cirle.scientific.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 常用的正则验证工具类，包括邮箱、手机、ip的合法性验证
 * 
 * @author zhouguofei
 * @since 2015-09-28
 */
public class RegValidateUtil {

	/**
	 * 验证邮箱格式合法性
	 * 
	 * @param email
	 *            待验证的邮箱
	 * @return 合法返回true，否则返回false
	 */
	public static boolean validateEmail(String email) {

		Pattern pattern = Pattern
				.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
		Matcher matcher = pattern.matcher(email);
		return matcher.matches();
	}

	/**
	 * 验证手机格式合法性,根据最新的手机号段严格验证
	 * 
	 * @param mobile
	 *            待验证的手机号
	 * @param strict
	 *            是否严格验证，true-严格按照最新的手机号段来验证，false-只验证基本格式
	 * @return 合法返回true，否则返回false
	 */
	public static boolean validateMobile(String mobile, boolean strict) {

		Pattern pattern = null;
		if (strict) {
			pattern = Pattern
					.compile("^((13[0-9])|(14[5,7])|(15[^4,\\D])|(17[0,6,7,8])|(18[0-9]))\\d{8}$");
		} else {
			pattern = Pattern.compile("^(1)\\d{10}$");
		}

		Matcher matcher = pattern.matcher(mobile);
		return matcher.matches();
	}

	/**
	 * 验证ip地址的合法性
	 * 
	 * @param ip
	 *            待验证的ip地址
	 * @return 合法返回true，否则返回false
	 */
	public static boolean validateIpAddress(String ip) {
		Pattern pattern = Pattern
				.compile("\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b");
		Matcher matcher = pattern.matcher(ip);

		return matcher.matches();
	}

}