我正在尝试使用 re.txt 将 Windows 不喜欢的文件路径(例如
。当我使用这个时:%$£^
)中的字符串中的所有字符替换为空字符串。子
import string
import re
name= '*example -name_with^additional£$characters'
for j in name:
if j in string.ascii_letters+string.digits+'_-':
name=re.sub(j,'',name)
正则表达式起作用并用空字符串替换所有字符。但是,由于我想替换 string.ascii_letters+string.digits+'_-'
中的字符,所以我需要使用 not
代替...
import string
import re
name= '*example -name_with^additional£$characters'
for j in name:
if j not in string.ascii_letters+string.digits+'_-':
name=re.sub(j,'',name)
但是,这给了我一个错误:
File "C:\Anaconda2\lib\re.py", line 155, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "C:\Anaconda2\lib\re.py", line 251, in _compile
raise error, v # invalid expression
error: unexpected end of regular expression
有人知道这是怎么回事吗?谢谢
最佳答案
出现此问题的原因是您尝试使用 *
模式来 re.sub
,并且它是无效的正则表达式模式,因为您无法量化任何内容(空位置)。
使用简单的替换
:
import string
name= '*example -name_with^additional£$characters'
for j in name:
if j not in string.ascii_letters+string.digits+'_-':
name=name.replace(j,'') # <- here
print(name)
关于python - 用否定替换条件(即使用 not)会导致 python re.sub 方法出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39098761/