The interviewer asked me to verify whether the user name is legal, so I directly took out the most basic and cumbersome code

package com.zhangsan.controller;

import org.apache.commons.lang.StringUtils;

public class Test {
    
    


    // 1、开头不能是数字
    // 2、包含大写、小写字母、数字
    // 3、至少一个特殊字符
    public static boolean testString(String s){
    
    
        String begin = s.substring(0,1);
        // 1、开头不能是数字
        boolean numeric = StringUtils.isNumeric(begin);
        if (numeric){
    
    
            return false;
        }
        // 2、包含大写、小写字母、数字
        char[] charArray = s.toCharArray();
        int specialCount = 0, lowerCount = 0, upperCount = 0, numberCount = 0;
        for (char c : charArray) {
    
    
            int ascValue = c;
            // System.out.println(ascValue);
            if((ascValue > 32 && ascValue < 48) || ascValue == 64){
    
    
                specialCount++;
            } else if (ascValue > 47 && ascValue < 58) {
    
    
                numberCount++;
            }else if (ascValue > 64 && ascValue < 91) {
    
    
                upperCount++;
            }else if (ascValue > 96 && ascValue < 123) {
    
    
                lowerCount++;
            }
        }
        return specialCount >= 1 && lowerCount >= 1 && upperCount >= 1 && numberCount >= 1;
    }

    public static void main(String[] args) {
    
    
        String s1 = "1@zhangsan"; // false
        String s2 = "Zhangsan@1"; // true
        System.out.println(testString(s1));
    }

}

Guess you like

Origin blog.csdn.net/weixin_44019553/article/details/131643473