正则表达式不会将字符'\\'

时间:2019-06-10 06:38:16

标签: python regex

我想从字符串中删除字符\\。我尝试了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)

我希望子方法用\\代替我的\\来清理我的字符串。

2 个答案:

答案 0 :(得分:4)

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

观察:

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"

答案 1 :(得分:0)

您可以尝试:

import re
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\\' '''
d = re.sub(r'\\', '', s)
print(d)

输出:

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'