Groovy: Generate random string from given character set

后端 未结 6 486
温柔的废话
温柔的废话 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

    This code is pure Groovy I found on the web:

    def key
    def giveMeKey(){
        String alphabet = (('A'..'N')+('P'..'Z')+('a'..'k')+('m'..'z')+('2'..'9')).join() 
        def length = 6
         key = new Random().with {
               (1..length).collect { alphabet[ nextInt( alphabet.length() ) ] }.join()
                 }
                return key
            }
    

    The return string is good enough for local use:

    BFx9PU
    MkbRaE
    FKvupt
    gEwjby
    Gk2kK6
    uJmzLB
    WRJGKL
    RnSUQT
    

提交回复
热议问题