[Tutor] Help with Python Regular Expressions

Brian Christopher Robinson brian@dungeoncrawl.org
Thu Jun 26 11:43:24 2003


I'm working on a Python script to automate the creation of new classes for 
my C++ project.  For the header files, I'd like to generate the #ifdef 
string for the header guard.  So if the class is called FooBar, I want to 
get the string FOO_BAR.  The basic rule is that wherever there is an 
uppercase letter, put an '_' in front of it.  The exception is the capitol 
at the beginning of the string.

Currently I have this:

def makeIfDefName(fileName):
     import re
     p = re.compile('([A-Z])')
     newFileName = p.sub(r'_\1', fileName)
     return newFileName.upper()

When given "FooBar" this returns "_FOO_BAR".  I could do it without regular 
expressions, I suppose, but I'd like to learn RE's too.


-- 
"It's hard to be disciplined when you lack respect for the world." - Matt 
on life