簡體   English   中英

如何檢查字符串是否僅包含字母數字字符和短划線?

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

我正在測試的字符串可以與[\\w-]+匹配。 我可以測試一個字符串是否符合Python中的這個,而不是有一個不允許的字符列表並測試它?

如果要針對正則表達式測試字符串,請使用re

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

Python也有正則表達式:

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

或者您可以創建允許的字符列表:

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

不使用純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'

或者在一行中:

''.join([c for c in string if c.isalnum() or c in ['-']])

為了測試字符串是否包含字母數字和破折號,我會使用

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