Use variable in regular expression

Antti Rasinen ars at iki.fi
Thu Aug 2 07:05:47 EDT 2007


On 2007-08-02, at 13:43, CarpeSkium at gmail.com wrote:

> I know I can use a variable in regular expressions. I want to use a
> regex to find something based on the beginning of the string. I am
> using yesterday's date to find all of my data from yesterday.
> Yesterday's date is 20070731, and assigned to the variable
> "yesterday_date". I want to loop thru a directory and find all of the
> yesterday's data ONLY IF the feature class has the date at the
> BEGINNING of the filename.
>

> ...

> I don't want the one's that start with "Copy". I can't figure out the
> syntax of inserting the "^" into the regex. I've tried all of the
> following, with no luck:
>
> re.compile(^yesterday_date)
> re.compile(r'^yesterday_date')
> re.compile(r'^[yesterday_date]')
> re.compile(r'[^yesterday_date]')

The first one is a syntax error (^ outside a string means the xor- 
operation). The rest are just strings containing the _string_  
'yesterday_date' and not the value of the variable. So you need to do  
some string formatting(*

search_str = '^%s' % yesterday_date # I'm assuming yesterday_date is  
a string.
re.compile(search_str)

*) http://docs.python.org/lib/typesseq-strings.html

-- 
[ ars at iki.fi <*> Antti Rasinen ]

This drone-vessel speaks with the voice and authority of the Ur-Quan.




More information about the Python-list mailing list