-3
如何創建一個正則表達式,使字符串不包含標點符號/特殊字符,例如* $ <,>? ! %[] | \?
rule = re.compile(r'')
如何創建一個正則表達式,使字符串不包含標點符號/特殊字符,例如* $ <,>? ! %[] | \?
rule = re.compile(r'')
您可以使用regex
或str.translate
這裏:
>>> from string import punctuation
>>> punctuation
'!"#$%&\'()*+,-./:;<=>[email protected][\\]^_`{|}~'
>>> strs = "[email protected]#$%sf*&"
>>> re.sub(r'[{}]'.format(punctuation),'',strs)
'fosf'
>>> strs.translate(None,punctuation)
'fosf'
已閱讀character classes tutorial。
rule = re.compile(r'^[^*$<,>?!%[]\|\\?]*$')
^
:字符串的起始。
[^ .... ]
:否定字符類 - 匹配除這些字符以外的任何內容。
*
:重複0次或更多次。
$
:字符串結束。
是這個名單詳盡?或者你想匹配所有隻包含字母a-zA-Z和可能數字0-9的字符串嗎? – mnagel
正則表達式只匹配或無法匹配字符串。你想要的是刪除某些字符,這不是正則表達式的意思,儘管Python沒有說清楚。 – jhoyla