简体   繁体   中英

“reverse” regular expression with JavaScript(node.js)

With regular expression like this /\\w/ I can match strings like a , q . Is there any idiomatic way to generate all the strings which match some regex in JS?

Don't think about infinite cases. I just want to describe some sets of possible symbols briefly.

something meaningful instead of

var s = ' !"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'

You can try the randexp library :

Randexp will generate a random string that matches a given RegExp Javascript object

See the demo:

 document.body.innerHTML = new RandExp(/\\w/).gen(); document.body.innerHTML += "<br/>" + new RandExp(/\\w/).gen(); document.body.innerHTML += "<br/>" + new RandExp(/[for]{3}/).gen(); document.body.innerHTML += "<br/>" + new RandExp(/I like (cats|dogs|mice)/).gen(); 
 <script src="https://github.com/fent/randexp.js/releases/download/v0.4.1/randexp.min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM