我想从正则表达式生成随机字符串。
示例:
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
答案 0 :(得分:5)
您可以查看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以获得a 可用的最大值。如果你想使用100以外的另一个int你 可以更改RandExp.prototype或RandExp中的max属性 实例
答案 1 :(得分:1)
rand
这里将接受一个length
,它将是字符串的长度,以及一些2项数组,每个都确定一个范围边界。然后返回一个字符串,该字符串仅包含所提供范围内的字符。
function rand(length, ...ranges) {
var str = ""; // the string (initialized to "")
while(length--) { // repeat this length of times
var ind = Math.floor(Math.random() * ranges.length); // get a random range from the ranges object
var min = ranges[ind][0].charCodeAt(0), // get the minimum char code allowed for this range
max = ranges[ind][1].charCodeAt(0); // get the maximum char code allowed for this range
var c = Math.floor(Math.random() * (max - min + 1)) + min; // get a random char code between min and max
str += String.fromCharCode(c); // convert it back into a character and append it to the string str
}
return str; // return str
}
console.log(rand(4, ["A", "Z"], ["0", "9"]));
console.log(rand(20, ["a", "f"], ["A", "Z"], ["0", "9"]));
console.log("Random binary number: ", rand(8, ["0", "1"]));
console.log("Random HEX color: ", "#" + rand(6, ["A", "F"], ["0", "9"]));
答案 2 :(得分:1)
您也可以尝试使用reregexp.js,它很好地支持正则表达式规则,甚至是类似这样的规则:/(?<test>[a-z]{2})\k<test>/
这是一个测试:
var reregexp = new RegexpParser('/^[0-9,A-Z]{4}$/')
console.log(reregexp.build());
console.log(reregexp.build());
console.log(reregexp.build());
<script src="https://cdn.jsdelivr.net/gh/suchjs/reregexp@master/dist/reregexp.min.js"></script>
答案 3 :(得分:0)
只需了解 @rpadovani 回答:
您可以查看randexp.js,它完全符合您的要求
运行此js片段,您会发现它生成这些字符串
1P
7P
3P
正则表达式^\d(?:\d|$)(?:P)?$
无法匹配
我确信这是一个很棒的球场尝试,但看起来不可信任
在肠道深处,有一些无法真正找到的途径
办法。
我还没有检查过其他更复杂的正则表达式 我从这个相当简单的例子开始,然后停止。
太糟糕了,如果有效的话会很好。
console.log(new RandExp(/^\d(?:\d|$)(?:P)?$/).gen());
<script src="https://github.com/fent/randexp.js/releases/download/v0.4.3/randexp.min.js"></script>