[Tutor] Help with Python Regular Expressions

Jeff Shannon jeff@ccvcorp.com
Thu Jun 26 12:47:02 2003


Brian Christopher Robinson wrote:

> 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. 


I realize that you said you'd like to learn REs, but this seems simple 
enough that REs are more trouble than they're worth.  Here's my version:

 >>> def MakeName(name):
...     result = []
...     for char in name:
...         if char.isupper():
...             if result != []:
...                 result.append('_')
...         result.append(char.upper())
...     return ''.join(result)
...
 >>> MakeName('FooBar')
'FOO_BAR'
 >>> MakeName('SomeLongSillyName')
'SOME_LONG_SILLY_NAME'
 >>>

Regular expressions are powerful and useful, to be sure, but they are 
also complex, and probably shouldn't be the first tool that's reached 
for.  "The simplest thing that can possibly work" is a good guiding 
principle to follow.

Jeff Shannon
Technician/Programmer
Credit International