Possible to insert variables into regular expressions?

Chris Lasher chris.lasher at gmail.com
Thu Dec 9 16:12:07 EST 2004


Hello,
I would like to create a set of very similar regular expression. In
my initial thought, I'd hoped to create a regular expression with a
variable inside of it that I could simply pass a string into by
defining this variable elsewhere in my module/function/class where I
compile the regular expression, thus making for an easy substitution.
However, still after JFGI'ing, I still cannot find the syntax to place
a variable inside a regular expression in Python. Is such a thing
possible, and if so what is the syntax to do it? If this is not
possible, what would be the Python way of swapping a small part of the
insides of a regexp without having to copy and paste the code to create
as many variations as necessary?

To make this more concrete, I think an example is in order. Let's say
I have a document like this

The Beatles
Rubber Soul
Track Listings
1. Drive My Car
2. Norwegian Wood (This Bird Has Flown)
3. You Won't See Me
4. Nowhere Man
5. Think for Yourself
6. Word
7. Michelle
8. What Goes On
9. Girl
10. I'm Looking Through You
11. In My Life
12. Wait
13. If I Needed Someone
14. Run for Your Life
Original Release Date: December 3, 1965
Number of Discs: 1
Label: Capitol
...

and I want to look for tracks that contain 'oo'. Then, maybe later, I
want to look for 'ee', or maybe 'ou'. All the regular expressions would
start by searching for a digit at the beginning of the line, and they
would allow for characters up until the desired two-letter vowel
combination, and then search for the two-letter vowel combination. How
can I provide for a way to "drop-in" the two-letter combination I want?
Thanks very much for your help and assistance in advance.

Chris




More information about the Python-list mailing list