我想从正则表达式生成一个随机字符串。
example:
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
你可以看看兰德普.js http://fent.github.io/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>
当然也有一些限制:
重复标记(例如 *、+ 和 {3,})具有无限的最大范围。
在本例中,randexp 查看其最小值并加 100 以获得
可用的最大值。如果你想使用 100 以外的其他 int
可以更改 RandExp.prototype 或 RandExp 中的 max 属性
实例。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)