Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate random strings that match a given regexp?

Duplicate:

Random string that matches a regexp

No, it isn't. I'm looking for an easy and universal method, one that I could actually implement. That's far more difficult than randomly generating passwords.


I want to create an application that takes a regular expression, and shows 10 randomly generated strings that match that expression. It's supposed to help people better understand their regexps, and to decide i.e. if they're secure enough for validation purposes. Does anyone know of an easy way to do that?

One obvious solution would be to write (or steal) a regexp parser, but that seems really over my head.

I repeat, I'm looking for an easy and universal way to do that.

Edit: Brute force approach is out of the question. Assuming the random strings would just be [a-z0-9]{10} and 1 million iterations per second, it would take 65 years to iterate trough the space of all 10-char strings.

like image 427
Michał Tatarynowicz Avatar asked Apr 14 '09 15:04

Michał Tatarynowicz


People also ask

Can we generate random string?

Using Java 8 StreamYou can also generate a random alphanumeric string of fixed length using streams in Java. A random string is generated by first generating a stream of random numbers of ASCII values for 0-9, a-z and A-Z characters.

How do you match a name in regex?

p{L} => matches any kind of letter character from any language. p{N} => matches any kind of numeric character. *- => matches asterisk and hyphen. + => Quantifier — Matches between one to unlimited times (greedy)


2 Answers

Parse your regular expression into a DFA, then traverse your DFA randomly until you end up in an accepting state, outputting a character for each transition. Each walk will yield a new string that matches the expression.

This doesn't work for "regular" expressions that aren't really regular, though, such as expressions with backreferences. It depends on what kind of expression you're after.

like image 66
Welbog Avatar answered Nov 14 '22 08:11

Welbog


Take a look at Perl's String::Random.

like image 21
moonshadow Avatar answered Nov 14 '22 09:11

moonshadow