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

风格不统一 提交于 2019-12-12 09:29:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!