Only accept alphanumeric characters and underscores for a string in python

Howeitzer picture Howeitzer · Jun 7, 2013 · Viewed 9.5k times · Source

I'm currently writing validation code for a tool parameter in ArcMap 10 (updateMessages) and need to prevent users from using non-alphanumeric characters within a string as it will be used to name a newly created field in a feature class.

I have so far used 'str.isalnum()' however this of course excludes underscores. Is there an efficient way to only accept alphanumeric characters and underscores?

if self.params[3].altered:
  #Check if field name already exists
  if str(self.params[3].value) in [f.name for f in arcpy.ListFields(str(self.params[0].value))]:
    self.params[3].setErrorMessage("A field with this name already exists in the data set.")
  #Check for invalid characters
  elif not str(self.params[3].value).isalnum():
    self.params[3].setErrorMessage("There are invalid characters in the field name.")   
  else:
    self.params[3].clearMessage()

return

Answer

bwind picture bwind · Jun 7, 2013

Try regular expressions:

import re
if re.match(r'^[A-Za-z0-9_]+$', text):
    # do stuff