How to create a random string from a regular expression

17,568

Solution 1

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.

Solution 2

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"]));

Solution 3

You can also have a try with reregexp.js, it support many newest regex features:

  • \u flag: e.g. /[\u{30}-\u{39}\u{2c}\u{41}-\u{5a}]{4}/u
  • Named group: e.g. /(?<named>[0-9,A-Z]{2})\k<named>/
  • Define a generator function and use the unicode property class: e.g. /\p{Script=Hani}/u

Here is a test:

var re = new ReRegExp(/^[0-9,A-Z]{4}$/, {
    extractSetAverage: true // this config make the '0-9' has chance ten times than the ',',otherwise they both have equal chance.          
});
console.log(re.build());
console.log(re.build());
console.log(re.build());
<script src="https://cdn.jsdelivr.net/gh/suchjs/reregexp@master/dist/reregexp.min.js"></script>
Share:
17,568
tahayk
Author by

tahayk

Updated on June 08, 2022

Comments

  • tahayk
    tahayk almost 2 years

    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
    
  • Admin
    Admin about 7 years
    This randexp.min.js is not to be trusted or used. I'd say there is more limitations than stated. Namely it gives results that are in error. Example: console.log(new RandExp(/^((0(?:[1-9]|$)|1(?:[0-2]|$))(?::(?:([0-5])(?:([0-9‌​])(?:\s([ap]m?)?)?)?‌​)?)?)$/).gen()); spits out 0: and 1: which the regex won't match.
  • NathanOliver
    NathanOliver over 5 years
    When offering you own library please disclose that it is yours.
  • suchjs
    suchjs over 5 years
    @NathanOliver thanks for your advice,i have changed the js file into a jsdelivr address :)
  • Kou Ariga
    Kou Ariga over 2 years
    /^[0-9,A-Z]{4}$/ could generate strings that include commas like 000,. In case you want alphanumeric strings, just use /[0-9A-Z]{4}/ instead.