如何检查字符串是否只包含字母数字字符和破折号?

时间:2020-12-22 20:17:08

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?

我正在测试的字符串可以与[\w-]+匹配。我是否可以测试一个字符串是否符合Python中的这个特性,而不是拥有一个不允许的字符列表并进行测试?

4 个解决方案

#1


24  

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

#2


5  

Python has regex as well:

Python也有regex:

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


2  

Without importing any module just using pure python, remove any none alpha, numeric except dashes.

不需要使用纯python导入任何模块,只需删除除破折号之外的任何空字符。

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


1  

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

#1


24  

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

#2


5  

Python has regex as well:

Python也有regex:

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


2  

Without importing any module just using pure python, remove any none alpha, numeric except dashes.

不需要使用纯python导入任何模块,只需删除除破折号之外的任何空字符。

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


1  

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