Use variable in regular expression

Steve Holden steve at holdenweb.com
Thu Aug 2 08:42:44 EDT 2007


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.
> 
> Sample strings:
> 20070731_test1
> Copy20070731_test1
> 20070731_test2
> Copy20070731_test2
> 20070731_test3
> Copy20070731_test3
> 
> 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]')
> 
> I don't know what I'm doing and I'm just guessing at this point. Can
> anyone help? Thanks.
> 
As is often the case, taking a larger look at the problem can reveal 
that Python has features that can help you without even getting down to 
more complex stuff.

You appear to require a list of the files whose names begin with a 
string representation of yesterday's date.

If you take a look at the glob module you will see that it has a glob() 
function, and if you were to call it as

     names = glob.glob(yesterday_date + "*")

it would return a list of the names of the files you are interested in.

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------




More information about the Python-list mailing list