gpt4 book ai didi

javascript - 如何从正则表达式创建随机字符串

转载 作者:行者123 更新时间:2023-11-30 07:13:17 30 4
gpt4 key购买 nike

我想从正则表达式中生成一个随机字符串。

例子:

random_string(/^[0-9]{4}$/) //==> 7895
random_string(/^[0-9]{4}$/) //==> 0804
random_string(/^[0-9,A-Z]{4}$/) //==> 9ZE5
random_string(/^[0-9,A-Z]{4}$/) //==> 84D6

最佳答案

可以看randexp.js ,它正是你想要的

console.log(new RandExp(/^[0-9]{4}$/).gen());
console.log(new RandExp(/^[0-9]{4}$/).gen());
console.log(new RandExp(/^[0-9,A-Z]{4}$/).gen());
console.log(new RandExp(/^[0-9,A-Z]{4}$/).gen());
<script src="https://github.com/fent/randexp.js/releases/download/v0.4.3/randexp.min.js"></script>

当然也有一些限制:

Repetitional tokens such as *, +, and {3,} have an infinite max range. In this case, randexp looks at its min and adds 100 to it to get a useable max value. If you want to use another int other than 100 you can change the max property in RandExp.prototype or the RandExp instance.

关于javascript - 如何从正则表达式创建随机字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43547777/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com