views:

366

answers:

3

I know you can generate all permutations from a list, using glob or Algorithm::Permute for example - but how do you generate all possible permutations from a regular expression?

I want to do like:

@perms = permute( "/\s[A-Z][0-9][0-9]/" );
sub permute( $regex ) {
    # code - put all permutations of above regex in a list
    return @list;
}
+5  A: 

See Section 6.5 (PDF) in Higher Order Perl. Consider buying the print book: It is a work of art.

There is also Regexp::Genex on CPAN.

Sinan Ünür
+2  A: 

Any possibly implementation should have a reasonable maximum length in mind for the generated strings. If there's a + or * anywhere in that regexp, the possibilities could be without end. Regexp::Genex considers this.

dlamblin
unfortunately "perl -MRegexp::Genex=:all -le 'print for strings("[a-z]")'" does not work though. I think it has bugs with () and [] sets.
wibble
A: 

None of the solutions I've encountered handle lookaheads; Regexp::Genex doesn't, nor does the solution here:

http://www.mail-archive.com/[email protected]/msg31051.html

While I agree that HOP is an awesome book, it's really only dealing with a small subset of regexes "out-of-the-box".

If anybody knows of one that handles lookaheads, that'd be great :/

The knapsack problem (known to be NP-complete) can trivially be translated into determining whether there exist any strings which are matched by a constructed regex (with lookaheads). In other words, it's too hard.
ephemient