Friday 24 May 2019

regex - java use Regular Expressions to generate a string




i want to generate random String who have this form





[A-Za-z0-9]{5,10}




I don't have any idea how to do it, i should use regular expressions or random function ?


Answer



I'd stick to a Java-solution in this case, something along the lines of:



private String allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGRHIJKLMNOPQRSTUVWXYZ0123456789";


public String getRandomValue(int min, int max) {
Random random = new Random();
int length = random.nextInt(max - min + 1) + min;
StringBuilder sb = new StringBuilder();
for(int i = 0; i < length; i++) {
sb.append(allowedChars.charAt(random.nextInt(allowedChars.length())));
}
return sb.toString();
}



You can call this with getRandomValue(5, 10);



I have not tried this code, since I have no IDE available



Note, if you're not apposed to using third party libraries, there are numerous available.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...