Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中使用正则表达式替换特殊字符_Python_Regex - Fatal编程技术网

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

在python中使用正则表达式替换特殊字符,python,regex,Python,Regex,为了学习,我尝试用下划线' List of characters= ~!@#$%^&*()+|}{:"?><-=[]\;',./ 无法做到这一点,我得到了上述错误 如何使用正则表达式替换字符串中的特殊字符您可以使用re.escape对字符串中的所有特殊正则表达式字符进行转义,然后将转义字符串括在[…]中,使其与其中任何一个匹配 >>> re.sub("[%s]" % re.escape('!~@#$%^&*()-+={}[]:;<.>?

为了学习,我尝试用
下划线'

List of characters= ~!@#$%^&*()+|}{:"?><-=[]\;',./
无法做到这一点,我得到了上述错误


如何使用正则表达式替换字符串中的特殊字符您可以使用
re.escape
对字符串中的所有特殊正则表达式字符进行转义,然后将转义字符串括在
[…]
中,使其与其中任何一个匹配

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

只需将其放入字符类中,并重新排列某些字符的位置(即
-
,转义
+
):

重新导入

table=“”“123~!@$%^&*()+|}{:”?>这是您的确切字符串吗?它没有任何引号。请尝试
table=“”…”
另外,开头的
123
是什么意思?请注意,
)-+
创建了一个无效的范围。始终将
-
放在字符类的结尾/开头。是的,使用字符类:)@tobias_k是的,它是精确的字符串,
123
前面没有任何内容。还有
\W
,它匹配所有的non字字符:
re.sub(r'\W','\u',一些字符串)
@Blurp好的点,但也可以替换,例如空格。可能会使用类似于
[^\W\s]
的内容,这取决于OP想要替换的内容。此外,似乎还有一些字符,如
不应该替换的内容(尽管这可能是问题中的一个错误).
>>> 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)
import re
table = """123~!@#$%^&*()+|}{:"?><-=[]\;',./"""

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