[Tutor] Generating all possible hits of a regex pattern

Barton David David.Barton at nottingham.ac.uk
Wed Jan 31 14:16:03 CET 2007


I don't suppose there's a nifty trick (exploiting the internal workings
of the re module perhaps) to generate all possible hits of a given regex
pattern?
 
Something like:
 
>>> import re
>>> mypattern=re.compile( "[AB]C{1,2}D?" )
>>> print list( all_pattern_generator( mypattern ) )
["AC","BC","ACC","BCC","ACD","BCD","ACCD","BCCD"]
 
Or would I have to do this the hard way, parsing the expression myself
etc?
 
I suppose you might have to be a little careful what expression you put
into this: "A*" would produce an infinite number of results. But if it
was in a generator function that wouldn't necessarily be a problem,
and/or perhaps I could pre-check 'mypattern' and warn if it was.
 
cheers
Dave
 
 
 
 
 
 

This message has been checked for viruses but the contents of an attachment
may still contain software viruses, which could damage your computer system:
you are advised to perform your own checks. Email communications with the
University of Nottingham may be monitored as permitted by UK legislation.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070131/4e6a25e1/attachment.htm 


More information about the Tutor mailing list