问题
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:
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
回答2:
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):
...
回答3:
Without importing any module just using pure python, remove any none alpha, numeric except dashes.
string = '#Remove-*crap?-from-this-STRING-123$%'
filter_char = lambda char: char.isalnum() or char == '-'
filter(filter_char, string)
# This returns--> 'Remove-crap-from-this-STRING-123'
Or in one line:
''.join([c for c in string if c.isalnum() or c in ['-']])
回答4:
To test if the string contains only alphanumeric and dashes, I would use
import re
found_s = re.findall('^[\w-]+$', s)
valid = bool(found_s) and found_s[0] == s
来源:https://stackoverflow.com/questions/10944438/how-do-i-check-if-a-string-only-contains-alphanumeric-characters-and-dashes