我一直在尝试使用正则表达式删除字符串的一部分。在
Heroes Chapter 91 - Rescue
我需要删除“章-号-”后的所有内容,我不能删除“-”之后的所有内容,因为我不确定标题是否总是“英雄”,所以,如果标题是“-新蜘蛛侠”,它会删除错误的部分。“-”也是如此,如果它删除“-”后面的所有内容,它可能会删除错误的部分。必须是“章节号-”。我不知道我是否解释得很好。在
不过,我试过这样做:
^{pr2}$但它返回Heroes
。在
title = "Heroes Chapter 91 - Rescue"
title = re.sub('Chapter (\d+).*', '', title)
但它再次返回Heroes
。在
有什么想法吗?在
有人把我和this question联系起来了,但我在那里找不到解决办法,如果有人看到了,请指出。我显然不是专家:)
最终解决方案:
title = "Heroes Chapter 91 - Rescue"
title = re.sub('(Chapter \d+).*', '\\1', title)
您可以在这里使用一个捕获组
( )
,并在替换中引用捕获的组。在试试看
尝试使用lookbehind:
如果re在lookbehind中不支持量词,那么使用cheshircat的解决方案。在
相关问题 更多 >
编程相关推荐