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
To check if given string contains only alphanumeric characters in Python, use String. isalnum() function. The function returns True if the string contains only alphanumeric characters and False if not. Following are the allowed Alphanumeric Characters.
A simple solution is to use regular expressions for removing non-alphanumeric characters from a string. The idea is to use the special character \W , which matches any character which is not a word character.
The isalnum() method returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9).
Python has a special sequence \w for matching alphanumeric and underscore. Please note that this regex will return true in case if string has alphanumeric and underscore. That's all about Python Regex to alphanumeric characters.
Try regular expressions:
import re
if re.match(r'^[A-Za-z0-9_]+$', text):
# do stuff
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With