尝试 sentence = regex.sub("[^[:graph:]\s]","",sentence,flags=regex.VERSION1)
您需要添加 flag
regex.VERSION1
我不确定regex
模块,但是你可以通过以下方式获取结果
import re
sentence = "I like math, I divided ÷ the power ³ by ¾"
sentence = re.sub("[^\x21-\x7E\s]","",sentence)
print(sentence)
这里有一张漂亮的图表http://www.regular-expressions.info/posixbrackets.html,展示如何将POSIX类转换为ASCII,re
模块可以理解。
[^\x21-\x7E\s]
和[^[:graph:]\s]
在你的情况下表现不同吗?对我来说,两者都会删除é和à。当我将\s
移到方括号外面时,它停止删除它们,只是因为我在测试字符串末尾输入它们。https://regex101.com/r/sM0yO2/2和https://regex101.com/r/sM0yO2/3 - Joseph Stover
sentence = regex.sub(r"(?V1)[^[:graph:]\s]","",sentence)
。 - Wiktor Stribiżew[:graph:]
应该匹配任何可见字符,但 PCRE 只计算 ASCII 字符。regex
库处理 POSIX 字符类时是完全支持 Unicode 的,除了一些似乎限制在原始 POSIX 定义中的 POSIX 字符类。(在您提供的链接中搜索“POSIX 字符类”即可了解详情。) - Alan Mooreregex
而不是re
)[现在正在检查Python3]。 - tmrlvi