How do I check if a string only contains alphanumeric characters and dashes?

q3d picture q3d · Jun 8, 2012 · Viewed 42.5k times · Source

The string I'm testing can be matched with [\w-]+. Can I test if a string conforms to this in Python, instead of having a list of the disallowed characters and testing for that?

Answer

math picture math · Jun 8, 2012

If you want to test a string against a regular expression, use the re library

import re
valid = re.match('^[\w-]+$', str) is not None