(10条消息) 利用ASCII和Unicode写正则表达式

例如,校验密码:必须同时包含字母、数字和特殊字符,6-16位

我们首先来看下特殊字符,一般情况下,我们指的特殊字符包括 !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ 这些,那这些字符用Unicode怎么表示呢?

\u0021-\u002F

\u003A-\u0040

\u005B-\u0060

\u007B-\u007E

从上面可以看出,这些特殊字符对应的Unicode编码为:

[\u0021-\u002F\u003A-\u0040\u005B-\u0060\u007B-\u007E]

那如果我们要用ASCII来表示呢?同样的,如下:

[\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E]

其实也可以直接用符号来表示:

[!-/:-@\[-`{-~]

接下来,我们完善整个表达式

^(?=.*[a-zA-Z])(?=.*\d)(?=.*[\u0021-\u002F\u003A-\u0040\u005B-\u0060\u007B-\u007E])[\u0021-\u007E]{6,16}$

^(?=.*[a-zA-Z])(?=.*\d)(?=.*[\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\x7E])[\x21-\x7E]{6,16}$

^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!-/:-@\[-`{-~])[!-~]{6,16}$

从上面三个正则来说,虽然匹配的结果一样,但ASCII的貌似比Unicode短一些,直接用符号表示的最短

代码验证(java实现)

  1. String regex="^(?=.*[a-zA-Z])(?=.*\\d)(?=.*[\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E])[\\u0021-\\u007E]{6,16}$";
  2. String[] arr={"123","123456","a698745","sd47897","sd687-=jk","&*(()_+","y<>@jkd7hsdfj"};
  3. for(String str:arr){
  4. System.out.println(str+"\t\t"+str.matches(regex));
  5. }

 

  1. String regex="^(?=.*[a-zA-Z])(?=.*\\d)(?=.*[\\x21-\\x2F\\x3A-\\x40\\x5B-\\x60\\x7B-\\x7E])[\\x21-\\x7E]{6,16}$";
  2. String[] arr={"123","123456","a698745","sd47897","sd687-=jk","&*(()_+","y<>@jkd7hsdfj"};
  3. for(String str:arr){
  4. System.out.println(str+"\t\t"+str.matches(regex));
  5. }

 

 

 

  1. String regex="^(?=.*[a-zA-Z])(?=.*\\d)(?=.*[!-/:-@\\[-`{-~])[!-~]{6,16}$";
  2. String[] arr={"123","123456","a698745","sd47897","sd687-=jk","&*(()_+","y<>@jkd7hsdfj"};
  3. for(String str:arr){
  4. System.out.println(str+"\t\t"+str.matches(regex));
  5. }

 

 

 

 

 

结果:

 

提示:[\u0021-\u007E]、[\x21-\x7E]、[!-~]

这三个正则的意思一样,都表示字母、数字和特殊字符

 

 

 

 

 

 

 

(0)

相关推荐