对re.sub中捕获组的反向引用未按预期工作

2024-09-30 14:23:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我想删除任何后跟数字的“\”

s = "somecharacters\15othercharacters"
s = re.sub(r"\\(\d+)", r"\1", s)

print(s)给了我othercharacters,而我期望的是somecharactersothercharacters

你能帮我修一下吗?
谢谢


Tags: re数字printsomecharactersothercharacterssomecharactersothercharacters
1条回答
网友
1楼 · 发布于 2024-09-30 14:23:46

我想你正在寻找这样的东西,正如你在问题的这一部分所要求的:

I want to remove any "\" followed by digits

import re
s = r"somecharacters\15othercharacters"
s = re.sub(r"\\\d+", '', s)
print(s)

当运行此输出时:

somecharactersothercharacters

相关问题 更多 >