匹配2到4个中文字符(用于匹配姓名):[\u4e00-\u9fa5]{2,4}
匹配电子邮箱:^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$(用于jsp) \\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*(用于java)
匹配手机号码:[0-9]{11}
以上为比较常用的正则表达式,下面实例介绍它怎么用:
String input = "张三丰,zhangs@qq.com,我要预订产品哦!";
//邮箱检测
String regex_email = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"; Pattern pattern_email = Pattern.compile(regex_email); Matcher matcher_email = pattern_email.matcher(input); while (matcher_email.find()) { email=matcher_email.group(); System.out.println("邮箱:"+matcher_email.group()); } //手机号检测 String regex_phone = "[0-9]{11}"; Pattern pattern_phone = Pattern.compile(regex_phone); Matcher matcher_phone = pattern_phone.matcher(input); while (matcher_phone.find()) { phone=matcher_phone.group(); System.out.println("手机号:"+matcher_phone.group()); }