Groovy: Generate random string from given character set

后端 未结 6 497
温柔的废话
温柔的废话 2021-01-31 14:33

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

  • Allowed charaters are: [A-Z0-9]
  • Length o
6条回答
  •  难免孤独
    2021-01-31 15:16

    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)
    

提交回复
热议问题