最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Generate a random string based on a regular expression - Stack Overflow

programmeradmin1浏览0评论

Is there any way of generating random text which satisfies provided regular expression.
I am looking for a function which works like below

var reg = Some Regular Expression  
var str = RandString(reg)

Is there any way of generating random text which satisfies provided regular expression.
I am looking for a function which works like below

var reg = Some Regular Expression  
var str = RandString(reg)
Share Improve this question asked Jan 22, 2012 at 8:10 ExceptionException 8,37924 gold badges87 silver badges141 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 14

I have seen fairly good solutions in perl and ruby on github, but I think there are technical issues that make a complete solution impossible. For example, /[0-9]+/ has an infinite upper bound, which is not practical for selecting random numbers from.

Never seen it in JavaScript, but you could translate.


EDIT: After googling for a few seconds... https://github.com/fent/randexp.js

if you know what the regular expression is, you can just generate random strings, then use a function that references the index of the letters and changes them as needed. Regex expressions vary widely, so it will be difficult to find one in particular that satisfies all possible regex.

Your question is pretty open so hopefully this steers you to the right solution. Get the current time (in seconds), MD5 it, check it against a REGEX, return the match.

Running Example: http://jsfiddle.net/MattLo/3gKrb/

Usage: RandString(/([A-Za-z])/ig); // expected to be a string

For JavaScript, the following modules can generate a random match to a regex:

  • pxeger
  • randexp.js
  • regexgen
发布评论

评论列表(0)

  1. 暂无评论