Python正则表达式用模式替换字符串

问题描述 投票:0回答:1

正则表达式是r'[A-z\d,\-.\ \/\n]{1,}',这个正则表达式将允许字母数字+一些特殊的字符。

我想替换不允许的字符。

我试过了,

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

输出为,

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

我想要原始字符串作为输出与替换特殊字符(不允许)与空格。

预期产量:ASGHB 3 JHDSD eyg ^ hdbcd v ^ B ^如何实现这一目标?

python regex python-2.7
1个回答
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.
© www.soinside.com 2019 - 2024. All rights reserved.