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

49

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

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

例如:A586FT3HS

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

6个回答

80
如果您不想使用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
当我使用这个时,我会收到“没有这样的DSL方法'nextInt'” 的错误提示。 - Chris F
你在 Jenkins 中使用它吗?我不知道这是否适用于 Jenkins。 - tim_yates
是的,我最终使用了Apache导入。 - Chris F
@ChrisF 你可能需要使用全名,或者导入:java.util.Random.nextInt() 我一会儿会测试这个。 - charlie_pl

64
import org.apache.commons.lang.RandomStringUtils

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

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

更新

如果你只想要字母数字字符包含在字符串中,可以将上述内容替换为

String randomString = org.apache.commons.lang.RandomStringUtils.random(9, true, true)

你也可以在标准的Groovy脚本中使用@Grab(group='commons-lang', module='commons-lang', version='2.4'),然后导入org.apache.commons.lang.RandomStringUtils - Nicolas Zozol
org.apache.commons.lang3.RandomStringUtils 现在拥有 randomAlphaNumeric(int count) - nerdherd
1
你可能会遇到 "org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use staticMethod org.apache.commons.lang.RandomStringUtils random int boolean boolean" 的错误。只需按照以下说明操作:https://dev59.com/eFoT5IYBdhLWcg3wrRKE#39412951 - GabLeRoux

8

针对SoupUI用户:

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);

对于特殊字符,如_、.、-,应采用哪种转义解决方案? - adrian filipescu

6
这里有一条单行命令/语句来生成随机文本字符串。
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()}

1

创建一个包含字母表的字符串,然后重复以下步骤9次:

  1. 创建一个随机
  2. 在你的字母表中找到相应的字符
  3. 将其添加到结果中

1

这段代码是我在网上找到的纯 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

那么您的字母表示例省略了一些字符,因为它们在某些字体中可能看起来相似?小写字母 'L' 和数字 '1'。还有大写字母 'O' 和数字 '0'?我理解您的想法了吗?(我知道这只是一个例子。) - Wyck
我不明白 i=0;i<50;i++ 循环的目的是什么? - Wyck
@Wyck 生成的字符串包含随机数量的大写字母、小写字母和数字。我已经更新了答案,你可以看到输出结果具有不同的大小写字母和数字集合。循环语句与答案无关。 - Abdelsalam Shahlol
2
我在Jenkins pipeline中遇到了两个问题。首先,我必须将.join()更改为.join(''),以避免出现hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: java.util.ArrayList.join() is applicable for argument types: () values: []的错误。其次,我必须重写代码,不使用with闭包,而是使用def rand = new Random(),然后使用rand.nextInt来避免出现java.lang.NoSuchMethodError: No such DSL method 'nextInt' found among steps的错误。 - Wyck

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接