【发布时间】:2017-11-14 21:00:51
【问题描述】:
只是为了学习,我正在尝试替换键盘中存在的所有特殊字符以替换为underscore'_'
List of characters= ~!@#$%^&*()+|}{:"?><-=[]\;',./
string I created:
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
无法这样做,我收到了上述错误。
如何使用正则表达式替换字符串中的特殊字符
【问题讨论】:
-
那是您的确切字符串吗?它没有任何引号。试试
table = """..."""还有,开头的123是怎么回事? -
请注意,
)-+创建了一个 invalid 范围。始终将-放在字符类的末尾/开头。是的,并使用一个字符类:) -
@tobias_k 是的,它是确切的字符串,
123前面没有任何内容 -
还有
\W,它匹配所有非单词字符:re.sub(r'\W', '_', some_string)。 docs.python.org/3/library/re.html#regular-expression-syntax -
@Blurp 好点,但这也将取代例如空白。不过可能会使用
[^\w\s]之类的东西,具体取决于OP 想要替换的内容。此外,似乎有像|这样的字符不能被替换(不过可能是问题中的错误)。