Cleanse Feature Class Names in Python
Today I ran across a problem with what should be a simple solution, but took me the better part of the morning to figure out...primarily because I was not familiar enough with regular expression matching. ArcGIS is pretty picky about feature class names, whether a feature class in a geodatabase or a shapefile. Either way, the feature class name must start with a letter and the rest of the characters can only be either letters, numbers or underscores.
My script is pulling names as part of selections from an external source. The names can and do break all of the aforementioned rules. Hence, I had a need for a name scrubber. Although it took more time than it should have, the end result is a two line function I have shared as a Gist.
[gist id=8786365]
Hopefully this saves you a little time and heartache! As always, have fun!
Update: Now I feel really stupid. Fifteen minutes after figuring this out, a colleague pointed out the arcpy.ValidateTableName function. Not only does it clean up invalid characters, it also checks existing tables for conflicting names. Again, learn from my labor and frustration, but if nothing else, have fun!