首页 > 解决方案 > 正则表达式不会子字符 '\\'

问题描述

我想从我的字符串中删除字符 \\。我试过 regextester 并且它匹配,https: //regex101.com/r/euGZsQ/1

 s = '''That\\'s not true. There are a range of causes. There are a        range of issues that we have to address. First of all, we have to identify, share and accept that there is a problem and that we\\''''

 pattern = re.compile(r'\\{2,}')
 re.sub(pattern, '', s)

我希望 sub 方法用什么来替换我的 \\ 来清理我的字符串。

标签: pythonregex

解决方案


问题是您的字符串本身未标记为原始字符串。因此,第一个\实际上逃脱了第二个。

观察:

import re

pattern = re.compile(r'\\{2,}')
s = r'''That\\'s not true. There are a range of causes. There are a        range of issues that we have to address. First of all, we have to identify, share and accept that there is a problem and that we\\'''
re.sub(pattern, '', s)

输出:

"That's not true. There are a range of causes. There are a        range of issues that we have to address. First of all, we have to identify, share and accept that there is a problem and that we"

推荐阅读