现在的位置: 首页 > 综合 > 正文

\t\tjava用Pattern和Matcher验证邮箱和手机号

2014年07月16日 ⁄ 综合 ⁄ 共 1469字 ⁄ 字号 评论关闭

package com.techcenter.regular;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

/**

* 验证邮箱和手机号

* @author xiaojunwei

*

*/

public class RegularUtil {

    /**

    * @param args

    */

    public static void main(String[] args) {     

       String email = "xiaojunwei_1987@sina.com.cn";   

       System.out.println(isEmail(email));

       String mobile = "13681297563";

       System.out.println(isMobile(mobile));

    }

   

    /**验证是否是正确的邮箱格式

    * @param email

    * @return true表示是正确的邮箱格式,false表示不是正确邮箱格式

    */

    public static boolean isEmail(String email){    

       // 1\\w+表示@之前至少要输入一个匹配字母或数字或下划线

       // 2(\\w+\\.)表示域名. 因为新浪邮箱域名是sina.com.cn

       //       所以后面{1,3}表示可以出现一次或两次或者三次.

       String regular = "\\w+@(\\w+\\.){1,3}\\w+";

       Pattern pattern = Pattern.compile(regular);

       boolean flag = false;

       if( email != null ){       

           Matcher matcher = pattern.matcher(email);

           flag = matcher.matches();      

       }     

       return flag;

    }  

   

    /**验证是否是手机号格式

    * 该方法还不是很严谨,只是可以简单验证

    * @param mobile

    * @return true表示是正确的手机号格式,false表示不是正确的手机号格式

    */

    public static boolean isMobile(String mobile){

       //当前运营商号段分配

       //中国移动号段 1340-1348 135 136 137 138 139 150 151 152 157 158 159 187 188 147

       //中国联通号段 130 131 132 155 156 185 186 145

       //中国电信号段 133 1349 153 180 189

       String regular = "1[3,4,5,8]{1}\\d{9}";

       Pattern pattern = Pattern.compile(regular);  

       boolean flag = false;

       if( mobile != null ){          

           Matcher matcher = pattern.matcher(mobile);

           flag = matcher.matches();         

       }

       return flag;

    }

}

抱歉!评论已关闭.