简体   繁体   English

如何检查字符串是否仅包含字母数字字符和短划线?

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

The string I'm testing can be matched with [\\w-]+ . 我正在测试的字符串可以与[\\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? 我可以测试一个字符串是否符合Python中的这个,而不是有一个不允许的字符列表并测试它?

If you want to test a string against a regular expression, use the re library 如果要针对正则表达式测试字符串,请使用re

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

Python has regex as well: Python也有正则表达式:

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):
    ...

Without importing any module just using pure python, remove any none alpha, numeric except dashes. 不使用纯python导入任何模块,删除任何无alpha,数字除了破折号。

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 ['-']])

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM