, app , , .
, :
1. , ;
2. , ;
3. , + ;
.
package com.test;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RandomStringUtil {
public static void main(String []args){
System.out.print(randomString(6,6,3));
System.out.println(matchAccountPattern("Liu123456"));
}
private static Object mLock = new Object();
private static Random random = null;
private static char[] numbersAndLetters = null;
public static final int TYPE_UNDEFINE = 0;
public static final int TYPE_NUMBER = 1;
public static final int TYPE_LETTER = 2;
public static final int TYPE_BOTH = 3;
public static String randomString(int minLength,int maxLength,int type){
String targetString =null;
if (minLength < 1) {
return targetString;
}
if (random == null) {
synchronized (mLock) {
if (random == null) {
random = new Random();
}
}
}
switch (type) {
case TYPE_NUMBER:
numbersAndLetters = ("0123456789").toCharArray();
break;
case TYPE_LETTER:
numbersAndLetters = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
break;
case TYPE_UNDEFINE:
case TYPE_BOTH:
default:
numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
break;
}
boolean isNumber = false;
boolean isLetter = false;
int len = getStringLength(minLength, maxLength, random);
char[] randBuffer = new char[len];
for (int i = 0; i < randBuffer.length; i++) {
randBuffer[i] = numbersAndLetters[random.nextInt(numbersAndLetters.length)];
if (randBuffer[i] >= 48 && randBuffer[i] <= 57) {
isNumber = true;
System.out.println(i+" randBuffer[i] "+randBuffer[i]+" isNumber "+isNumber);
}
if ((randBuffer[i] >= 65 && randBuffer[i] <= 90)||(randBuffer[i] >= 97 && randBuffer[i] <= 122)) {
isLetter = true;
System.out.println(i+" randBuffer[i] "+randBuffer[i]+" isLetter "+isLetter);
}
}
targetString = new String(randBuffer);
if (type == TYPE_BOTH) {
if (!isNumber||!isLetter){
targetString= randomString(maxLength, minLength, type);
}
}
return targetString;
}
/**
*
*
* @param minLength
* @param maxLength
* @param random
* @return
*/
private static int getStringLength(int minLength, int maxLength, Random random) {
if (maxLength < minLength) {
return 0;
}
int[] lengthArray = new int[maxLength - minLength + 1];
for (int a = 0; a <= maxLength - minLength; a++) {
lengthArray[a] = minLength + a;
}
return lengthArray[random.nextInt(lengthArray.length)];
}
public static boolean matchPassWordPattern(String userAccount) {
String regex = "^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]{6,16})$";
Pattern pattern = Pattern.compile(regex);
Matcher m = pattern.matcher(new String(userAccount));
return m.matches();
}
public static boolean matchAccountPattern(String userAccount) {
String regex = "^[a-z0-9A-Z]{8,12}$";
Pattern pattern = Pattern.compile(regex);
Matcher m = pattern.matcher(new String(userAccount));
return m.matches();
}
}