我是靠谱客的博主 成就巨人,最近开发中收集的这篇文章主要介绍Java工具类-随机字符串工具类,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

1.随机字符串使用场景

  • 短信验证码、校验码等随机字符
    var code = “807a5ce7-7642-49da-b1d4-c444c3d8c723”
package com.search.common.utils;

import java.util.Random;

/**
 * @author ZhangSan_Plus
 * @version 1.0
 * @className RandomUtils
 * @description TODO  随机字符工具类
 * @date 2020/10/26 19:13
 **/
public class RandomUtils {
    private static final String MATCHES_NO = ".*[a-z]{1,}.*";
    private static final String MATCHES_TWO = ".*[A-Z]{1,}.*";
    private static final String MATCHES_THREE = ".*[0-9]{1,}.*";
    private static final String REGULAR_CHAR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    private static final String NO_COUNT_CHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    private static final String UP_LETTER_CHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String NUMBER_CHAR = "1234567890";

    /**
     * 根据length来生成随机长度字符
     *
     * @param length
     * @return java.lang.String
     * @throws
     * @author ZhangSan_Plus
     * @date 19:15 2020/10/26
     **/
    public static String generatePassword(int length) {
        String result;
        result = getRandomPassword(length);
        if (result.matches(MATCHES_NO) && result.matches(MATCHES_TWO) && result.matches(MATCHES_THREE)) {
            return result;
        }
        return generatePassword(length);
    }

    public static String getRandomPassword(int length) {
        char[] charBuffer = REGULAR_CHAR.toCharArray();
        StringBuilder sb = new StringBuilder();
        Random r = new Random();
        for (int x = 0; x < length; ++x) {
            sb.append(charBuffer[r.nextInt(charBuffer.length)]);
        }
        return sb.toString();
    }


    public static String getRandomNo(int numberLength,int letterLength) {
        int nums= numberLength;
        int letter = letterLength;
        char[] charBuffer = NO_COUNT_CHAR.toCharArray();
        StringBuilder sb = new StringBuilder();
        Random r = new Random();
        for (int x = 0; x < numberLength+letterLength; x++) {
            int i = r.nextInt(charBuffer.length);
            sb.append(charBuffer[i]);
            if (48<=charBuffer[i]&&charBuffer[i]<=57){
                nums--;
            }else {
                letter--;
            }
            if (nums==0){
                charBuffer = UP_LETTER_CHAR.toCharArray();
            }else if (letter==0){
                charBuffer = NUMBER_CHAR.toCharArray();
            }
        }
        return sb.toString();
    }
}

最后

以上就是成就巨人为你收集整理的Java工具类-随机字符串工具类的全部内容,希望文章能够帮你解决Java工具类-随机字符串工具类所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(38)

评论列表共有 0 条评论

立即
投稿
返回
顶部