2017-12-18 206 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.