Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a random string from a regular expression

I want to generate a random string form a regular expression.

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
like image 702
tahayk Avatar asked Apr 21 '17 16:04

tahayk


2 Answers

You can take a look to randexp.js, it does exactly what you want

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>

Of course there are some limitations:

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.

like image 190
rpadovani Avatar answered Nov 10 '22 09:11

rpadovani


rand here will accepts a length which will be the length of the string, and a number of 2-items arrays, each determine a range boundaries. Then return a string which only consists of the characters in the ranges provided.

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"]));
like image 44
ibrahim mahrir Avatar answered Nov 10 '22 08:11

ibrahim mahrir