2013-07-05 63 views
-3

如何創建一個正則表達式,使字符串不包含標點符號/特殊字符,例如* $ <,>? ! %[] | \?

rule = re.compile(r'') 
+0

是這個名單詳盡?或者你想匹配所有隻包含字母a-zA-Z和可能數字0-9的字符串嗎? – mnagel

+0

正則表達式只匹配或無法匹配字符串。你想要的是刪除某些字符,這不是正則表達式的意思,儘管Python沒有說清楚。 – jhoyla

回答

2

您可以使用regexstr.translate這裏:

>>> from string import punctuation 
>>> punctuation 
'!"#$%&\'()*+,-./:;<=>[email protected][\\]^_`{|}~' 

>>> strs = "[email protected]#$%sf*&" 

>>> re.sub(r'[{}]'.format(punctuation),'',strs) 
'fosf' 

>>> strs.translate(None,punctuation) 
'fosf' 
1

已閱讀character classes tutorial

rule = re.compile(r'^[^*$<,>?!%[]\|\\?]*$') 

^:字符串的起始。
[^ .... ]:否定字符類 - 匹配除這些字符以外的任何內容。
*:重複0次或更多次。
$:字符串結束。

相關問題