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

tah*_*ayk 1 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
Run Code Online (Sandbox Code Playgroud)

rpa*_*ani 6

你可以看看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());
Run Code Online (Sandbox Code Playgroud)
<script src="https://github.com/fent/randexp.js/releases/download/v0.4.3/randexp.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

当然有一些限制:

诸如*,+和{3,}之类的重复标记具有无限的最大范围.在这种情况下,randexp查看其最小值并向其添加100以获得可用的最大值.如果要使用100以外的其他int,可以更改RandExp.prototype或RandExp实例中的max属性.


ibr*_*rir 6

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"]));
Run Code Online (Sandbox Code Playgroud)