Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy: Generate random string from given character set

Using Groovy, I'd like to generate a random sequence of characters from a given regular expression.

  • Allowed charaters are: [A-Z0-9]
  • Length of generated sequence: 9

Example: A586FT3HS

However, I can't find any code snippet which would help me. If using regular expressions is too complicated, I'll be fine defining the allowed set of characters manually.

like image 537
Robert Strauch Avatar asked Nov 15 '11 14:11

Robert Strauch


People also ask

How do you generate random strings?

Using the random index number, we have generated the random character from the string alphabet. We then used the StringBuilder class to append all the characters together. If we want to change the random string into lower case, we can use the toLowerCase() method of the String .

How do you generate a random string of characters in Java?

Using randomUUID() java. util. UUID is another Java class that can be used to generate a random string. It offers a static randomUUID() method that returns a random alphanumeric string of 32 characters.


2 Answers

If you don't want to use apache commons, or aren't using Grails, an alternative is:

def generator = { String alphabet, int n ->   new Random().with {     (1..n).collect { alphabet[ nextInt( alphabet.length() ) ] }.join()   } }  generator( (('A'..'Z')+('0'..'9')).join(), 9 ) 

but again, you'll need to make your alphabet yourself... I don't know of anything which can parse a regular expression and extract out an alphabet of passing characters...

like image 96
tim_yates Avatar answered Oct 06 '22 08:10

tim_yates


import org.apache.commons.lang.RandomStringUtils  String charset = (('A'..'Z') + ('0'..'9')).join() Integer length = 9 String randomString = RandomStringUtils.random(length, charset.toCharArray()) 

The imported class RandomStringUtils is already on the Grails classpath, so you shouldn't need to add anything to the classpath if you're writing a Grails app.

Update

If you only want alphanumeric characters to be included in the String you can replace the above with

String randomString = org.apache.commons.lang.RandomStringUtils.random(9, true, true) 
like image 34
Dónal Avatar answered Oct 06 '22 07:10

Dónal