Groovy:从给定的字符集生成随机字符串

时间:2011-11-15 14:47:34

标签: string groovy random

使用Groovy,我想从给定的正则表达式生成随机字符序列。

  • 允许的字符为:[A-Z0-9]
  • 生成序列的长度:9

示例:A586FT3HS

但是,我找不到任何可以帮助我的代码段。如果使用正则表达式太复杂,我可以手动定义允许的字符集。

5 个答案:

答案 0 :(得分:60)

如果您不想使用apache commons,或者不使用Grails,则可以选择:

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

generator( (('A'..'Z')+('0'..'9')).join(), 9 )

但同样,你需要自己创建alphabet ...我不知道任何可以解析正则表达式并提取出字符串的字母......

答案 1 :(得分:44)

import org.apache.commons.lang.RandomStringUtils

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

导入的类RandomStringUtils已经在Grails类路径中,因此如果您正在编写Grails应用程序,则不需要向类路径添加任何内容。

更新

如果您只想在字符串中包含字母数字字符,则可以用

替换上面的字符
String randomString = org.apache.commons.lang.RandomStringUtils.random(9, true, true)

答案 2 :(得分:1)

然后使用您的字母创建一个字符串 这样做9次:

  1. 创建random号码
  2. 在您的字母表中找到the corresponding character
  3. Append结果

答案 3 :(得分:1)

这是一个生成随机文本字符串

的单行命令/语句
print new Random().with {(1..9).collect {(('a'..'z')).join()[ nextInt((('a'..'z')).join().length())]}.join()}

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

答案 4 :(得分:0)

这段代码是我在网上找到的纯粹的Groovy:

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
        }

返回字符串足以供本地使用:

BFx9PU
MkbRaE
FKvupt
gEwjby
Gk2kK6
uJmzLB
WRJGKL
RnSUQT