Java用正则表达式写简单账号密码注册判断

Java写简单账号密码注册判断 菜鸟刚学的表达式 练手代码.

  1 /*在注册时通常要验证用户名和密码是否合法,运用学习过的知识完成如下操作:
  2 
  3  用户名长度大于等于6位,必须包含数字和英文字母
  4 
  5  密码长度大于等于8位,必须包含特殊符合_或者$,英文字母以及数字
  6 
  7  以上两个条件同时成立注册才能成功。
  8 
  9 
 10 
 11  * */
 12 
 13 import java.util.Scanner;
 14 
 15 import java.util.regex.Matcher;
 16 
 17 import java.util.regex.Pattern;
 18 
 19 
 20 
 21 public class 作业3 {
 22 
 23 public static void main(String[] args) {
 24 
 25 Scanner sr = new Scanner(System.in);
 26 
 27 while (true) {
 28 
 29 System.out.println("请输入用户名:");
 30 
 31 
 32 
 33 String userName = sr.next();// 接受用户注册时输入的用户名
 34 
 35 Pattern p = Pattern.compile("[a-zA-Z][0-9]");
 36 
 37 Matcher m = p.matcher(userName);
 38 
 39 if (userName.length() < 6) {
 40 
 41 System.out.println("用户名长度需要大于6");
 42 
 43 continue;
 44 
 45 } else if (m.find()) {
 46 
 47 System.out.println("用户名输入正确.");
 48 
 49 break;
 50 
 51 } else {
 52 
 53 System.out.println("没有包含数字或者字母");
 54 
 55 continue;
 56 
 57 }
 58 
 59 }
 60 
 61 
 62 
 63 while (true) {
 64 
 65 System.out.println("请输入密码:");
 66 
 67 String userPass = sr.next();
 68 
 69 
 70 
 71 Pattern p1 = Pattern.compile("[a-zA-Z][0-9]");
 72 
 73 Pattern p2 = Pattern.compile("[$]");
 74 
 75 Pattern p3 = Pattern.compile("[_]");
 76 
 77 
 78 
 79 Matcher m1 = p1.matcher(userPass);
 80 
 81 Matcher m2 = p2.matcher(userPass);
 82 
 83 Matcher m3 = p3.matcher(userPass);
 84 
 85 
 86 
 87 if (userPass.length() < 8) {
 88 
 89 System.out.println("密码需要大于8位");
 90 
 91 continue;
 92 
 93 } else if (m1.find()  && (m2.find() || m3.find()) ) {
 94 
 95 System.out.println("注册成功");
 96 
 97 break;
 98 
 99 } else {
100 
101 System.out.println("密码需要包含符号_或者$ 且不能缺少字母和数字");
102 
103 continue;
104 
105 }
106 
107 }
108 
109 }
110 
111 }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。