1

I would like to check if a string matches part of a family of strings described by a regular expression.

The desired behavior would be something like:

>>> re.findall("hi", "h[ia]t")
["hi"]
>>> re.findall("at", "h[ia]t")
["at"]
>>> re.findall("hat", "h[ia]t")
["hat"]
>>> re.findall("cat", "h[ia]t")
[]

but the second argument to re.findall() is interpreted literally.

Of course in the simple example above I could explicitly check against both "hit" and "hat", but for more complicated expressions that seems unwieldy.

DMack
  • 1,117
  • 1
  • 10
  • 14

1 Answers1

3

Regular expressions are not generators. You can match a string versus a regex but you cannot construct all strings that match a given regular expression. You probably need shell-like brace expansion, but I don't think something like that is provided in the stdlib (fnmatch is close but offers only matching).

wRAR
  • 25,009
  • 4
  • 84
  • 97
  • 1
    Nitpick: you _can_ construct all strings that match a given regex for the [regular languages](http://en.wikipedia.org/wiki/Regular_language), e.g. with [a "generating mode" DFA](http://en.wikipedia.org/wiki/Deterministic_finite_automaton#Accept_and_Generate_modes). (Of course, this depends on what you mean by "construct all" for a set that is often infinite.) There's some practical discussion of this [on this question](http://stackoverflow.com/questions/492716/reversing-a-regular-expression-in-python). Agree that OP doesn't really need this and just wants shell-style expansion, though. – Danica Feb 15 '13 at 01:54