Groovy: Generate random string from given character set

我是研究僧i 提交于 2020-01-11 15:48:49

问题


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.


回答1:


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...




回答2:


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)



回答3:


For SoupUI users:

def generator = { String alphabet, int n ->
  new Random().with {
    (1..n).collect { alphabet[ nextInt( alphabet.length() ) ] }.join()
  }
}
randomValue = generator( (('A'..'Z')+('0'..'9')+('a'..'z')).join(), 15 )
testRunner.getTestCase().setPropertyValue("randomNumber", randomValue);



回答4:


Create a string with your alphabet, then do this 9 times:

  1. Create a random number
  2. Find the corresponding character in your alphabet.
  3. Append it to the result



回答5:


Here is a single line command/statement to generate random text string

print new Random().with {(1..9).collect {(('a'..'z')).join()[ nextInt((('a'..'z')).join().length())]}.join()}

or

def randText = print new Random().with {(1..9).collect {(('a'..'z')).join()[ nextInt((('a'..'z')).join().length())]}.join()}



回答6:


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


来源:https://stackoverflow.com/questions/8138164/groovy-generate-random-string-from-given-character-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!