java常用正则表达式

经常用到的正则表达式的汇总,后面还会继续补充:
 
1、校验用户名,只能输入数字、字母、汉字、_-,长度在1~20.
        String userName = "wsdf";
        String regex = "^[a-zA-Z0-9-_\\u4e00-\\u9fa5]{1,20}$";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(userName);
       
        System.out.println(userName.length());
        System.out.println(m.matches());

2、校验指定的字符串,长度在1到7之间,并且只能输入1到7之间的数字,当中不能存在重复数字。 
        String temp = "0123456";       
        String regex = "^(?=[1-7])(?:([1-7])(?!.*?\\1)){1,7}$";
        Pattern pattern = Pattern.compile(regex,Pattern.MULTILINE);         
        Matcher m = pattern.matcher(temp);
       
        System.out.println(m.matches());

3、匹配时间格式:HHmmss
   String regex=""^([0-1]?[0-9]|[2][0-3])([0-5][0-9])([0-5][0-9])$"";

你可能感兴趣的:(java,正则表达式,String,regex)