Groovy: Generate random string from given character set

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…

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)