使用Groovy,我想从给定的正则表达式中生成一个随机字符序列。
- 允许使用的字符为:
[A-Z0-9]
- 生成的序列长度为:9
例如:A586FT3HS
然而,我找不到任何能帮助我的代码片段。如果使用正则表达式过于复杂,我可以手动定义允许使用的字符集。
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
… 我不知道是否有任何可以解析正则表达式并提取通过字符的字母表的工具...
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)
@Grab(group='commons-lang', module='commons-lang', version='2.4')
,然后导入org.apache.commons.lang.RandomStringUtils
。 - Nicolas Zozolorg.apache.commons.lang3.RandomStringUtils
现在拥有 randomAlphaNumeric(int count)
。 - nerdherd针对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);
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()}
这段代码是我在网上找到的纯 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
i=0;i<50;i++
循环的目的是什么? - Wyck.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