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


Question

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?

1
21
6/8/2012 7:06:33 AM

Accepted Answer

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
31
6/8/2012 7:26:37 AM

Python has regex as well:

import re
if re.match('^[\w-]+$', s):
    ...

Or you could create a list of allowed characters:

from string import ascii_letters
if all(c in ascii_letters+'-' for c in s):
    ...

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon