2017-12-18 137 views
0

正則表達式是r'[A-z\d,\-.\ \/\n]{1,}',這個正則表達式將允許字母數字+一些特殊的字符。Python的正則表達式替換字符串與模式

我想替換不允許的字符。

我都試過了,

re.sub(r'[A-z\d,\-.\ \/\n]{1,}', ' ', 'ASGHB 3 JHDSD eyg && ^&*hdbcd v%^&*B#$%^') 

給出作爲輸出,

' && &* % &* #$% ' 

我想原始字符串作爲替換爲特殊字符(這是不允許的)用空格輸出。

預期產出:ASGHB 3 JHDSD eyg ^hdbcd v^B ^ 如何實現這一目標?

+3

'應用re.sub(R '[^ AZ \ d,\ - \ \/\ n] {1,}', '',「ASGHB 3 JHDSD EYG && ^&* hdbcd v%^&* B#$%^')'=>''ASGHB 3 JHDSD eyg^hdbcd v^B ^''?你應該給你預期的結果。 – Silencer

+1

也不要使用'[A-z]',否則你就會知道它實際做了什麼。 –

+0

@Silencer謝謝。 – fledgling

回答

3

你可以找到所有關於應用re.sub here

所以你的問題。你應該用你的^集之前:

If the first character of the set is '^', all the characters that are not in the set will be matched. 
For example, [^5] will match any character except '5', and [^^] will match any character except '^'. 
^ has no special meaning if it’s not the first character in the set.