?/\'"', '_', table) Traceback -6ren">
gpt4 book ai didi

python - python中使用正则表达式替换特殊字符

转载 作者:行者123 更新时间:2023-11-30 22:26:13 26 4
gpt4 key购买 nike

仅供学习,我尝试将键盘中存在的所有特殊字符替换为下划线'_'

List of characters= ~!@#$%^&*()+|}{:"?><-=[]\;',./

我创建的字符串:

table = """123~!@#$%^&*()+|}{:"?><-=[]\;',./"""

import re

table1= re.sub(r'!~@#$%^&*()-+={}[]:;<.>?/\'"', '_', table)

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.7/re.py", line 151, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "/usr/lib64/python2.7/re.py", line 242, in _compile
raise error, v # invalid expression
sre_constants.error: unexpected end of regular expression

无法这样做,我收到上述错误。

如何使用正则表达式替换字符串中的特殊字符

最佳答案

您可以使用 re.escape 转义字符串中的所有特殊正则表达式字符,然后将转义的字符串括入 [...] 中,以便它匹配任何其中。

>>> re.sub("[%s]" % re.escape('!~@#$%^&*()-+={}[]:;<.>?/\''), '_', table)
'123____________|___"_______\\__,__'

但是,由于您并未真正将该正则表达式用作正则表达式,因此您可能只是检查每个字符是否在该字符串中:

>>>''.join("_" if c in '!~@#$%^&*()-+={}[]:;<.>?/\'' else c for c in table)
'123____________|___"_______\\__,__'

或者为了使查找更快一点,请首先根据该字符串中的字符创建一个:

>>> bad_chars = set('!~@#$%^&*()-+={}[]:;<.>?/\'')
>>> ''.join("_" if c in bad_chars else c for c in table)

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

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