P is for Practical | |
PerlMonks |
Generating regex strings with a regexby bsb (Priest) |
on Aug 27, 2003 at 08:47 UTC ( [id://286981]=CUFP: print w/replies, xml ) | Need Help?? |
You want the list of strings which may match a regex.
The code for /^ab?(c|d)$/ is
This isn't reusable code, just a trick I found interesting and worth exploring. See the discussion (and code!) at Regexp generating strings? for some alternatives. The idea is to (manually) replace the atoms with code assertions, building up a hyotheical match, printing it and then failing in order to backtrack and try again. Brad Update: Regexp::Genex A more complex example follows, first some notes. The above will produce a warning "Quantifier unexpected on zero-length expression..." under -w because of the (?{$^R.b})?. Suppress it with "no warnings 'regexp';" The $^R variable contains the result of the last (?{}) assert and is localized for backtracking. (My first version had (?{ local $_ = $_ . "b" }) instead) I tried the more complex /reg(ular\s+)?exp?(ression)?/ but ran into a few interesting, but so far surmountable problems. Firstly, I haven't tried to tackle classes such as \s yet. I changed it to '_'. (YAPE::Regex has expanded classes) I couldn't convince perl to repeatedly run zero-width assertions at the same position in the string. To see why search for "infinite" in perlre :). (If anyone knows how, let me know). To work around I made a string of 'a's and tacked an 'a' onto each quantified assertion. A happy side-effect is that the length of the input string bounds the quantifiers (somehow, but I ain't doing the math). Also, the '*' quantifier is apparently optimized to not try to repeatedly match in the same position. I use {0,3} instead, as it isn't optimized. perlre again. Greediness controls the search/display order.
I'm looking for a good impossible assertion to put
at the end. Currently, (?!a)(?=a) since the obvious
'x' is also optimized. perl -Mre=debug tells why: I might be able to avoid the 'a's with m/.../g and resetting pos. I haven't investigated, but I doubt it. Output </readmore
Back to
Cool Uses for Perl
|
|