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

标签 javascript regex ecmascript-6

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

例子:

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/

相关文章:

javascript - 帮助理解 Javascript 不寻常的函数声明语法

java - 如何在没有正则表达式的情况下拆分字符串

.net - 从正则表达式范围中排除某些字符

javascript - 将变量分配给 'import' ed ES2015 模块

javascript - 使用 jQuery 从外部 JSON 站点获取数据,Singleton 类

javascript - 对象索引并使用 youtube api 接下来播放

javascript - ES6 Javascript以多个名称导入相同的js文件

javascript - react +Javascript :-Component will update is getting called too many times causing my application to crash

javascript - 错误 : First row is not an array. Google 饼图

javascript - 在 Javascript 中获取第一个数字出现后的子字符串