写一个javaweb代码为大小写字母、数字、#*@!组成,长度至少是8,每个类型至少出现一次正则表达式
时间: 2024-05-15 19:17:51 浏览: 17
下划线和破折号生成一个随机的字符串,长度为10个字符。
思路:
1.定义一个包含大小写字母、数字、下划线和破折号的字符串数组;
2.生成长度为10的随机字符串,即随机取10个字符,每次从数组中随机选择一个并拼接到字符串上;
3.将生成的随机字符串输出或存入数据库。
代码:
```java
import java.util.Random;
public class RandomStringUtil {
private static final String[] CHARS = {
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "_", "-"
};
public static String generateRandomString(int length) {
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < length; i++) {
int index = random.nextInt(CHARS.length);
sb.append(CHARS[index]);
}
return sb.toString();
}
}
```
使用示例:
```java
public class Main {
public static void main(String[] args) {
String randomString = RandomStringUtil.generateRandomString(10);
System.out.println(randomString);
}
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)