python - 用否定替换条件(即使用 not)会导致 python re.sub 方法出错

标签 python regex string

我正在尝试使用 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 demo

关于python - 用否定替换条件(即使用 not)会导致 python re.sub 方法出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39098761/

相关文章:

python - 保留索引-字符串对应关系 spark 字符串索引器

regex - Nginx 使用什么正则表达式引擎?

java - 需要字符串缓冲区帮助

c# - 如何知道字符串的大小(以字节为单位)?

python - 使用 lambda 表达式在 Python 中实现 string contains 函数

python - 在代码级别或 Nginx 级别保护 OTP API 的安全?

c - 在 C 中使用 scanf 的正则表达式

javascript - 正则表达式: grab part of string

java - 比较字符串和对象属性

python - 如何在 AWS Glue 中使用外部 Python 库?