gpt4 book ai didi

python - 不被正则表达式替换的特殊字符

转载 作者:行者123 更新时间:2023-11-28 22:43:44 24 4
gpt4 key购买 nike

我正在尝试从字符串中过滤一些特殊字符,并且我正在使用以下代码和正则表达式条件。

我原以为它会过滤掉除 -+# 之外的所有字符,但还有一些字符未被过滤。

text = "This is a long string~!@#$%^&*()_+|\=-{}[];':<>?with special characters"

print sub(r'[^a-zA-Z0-9 -+#]+', '', text)

显示的结果是:

This is a long string!#$%&*()+'with special characters

我期望打印出来的是:

This is a long string with #+- special characters

任何人都可以解释为什么会发生这种情况以及如何更正我的正则表达式或代码以过滤掉剩余的字符吗?

最佳答案

您不得在字符类中间使用未转义的连字符,使用:

print re.sub(r'[^a-zA-Z0-9 +#-]+', '', text)

关于python - 不被正则表达式替换的特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30285866/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com