Python-匹配最后一个单词并从上一行中删除

Python-匹配最后一个单词并从上一行中删除,python,match,Python,Match,我正在尝试匹配最后一个单词并从上一行中删除 import re # regex to select words with _- line = re.compile('s/^(\w+(?:[-_]\d+)?)\n(?=.*\1\b)//gm;') here_text = '''befall_fallen-fell closing-round Line - Eddying, dizzying, closing-round

我正在尝试匹配最后一个单词并从上一行中删除

import re

# regex to select words with _-
line = re.compile('s/^(\w+(?:[-_]\d+)?)\n(?=.*\1\b)//gm;')

here_text = '''befall_fallen-fell
               closing-round
               Line - Eddying, dizzying, closing-round
               laughter-laugh_laugh
               Line - With soft and drunken laughter-laugh_laugh
               laughter-laugh_laugh
               befall_fallen-fell
               Line - Veiling all that may befall_fallen-fell'''
输入

输出尝试

befall_fallen-fell
Line - Eddying, dizzying, closing-round
Line - With soft and drunken laughter-laugh_laugh
laughter-laugh_laugh
Line - Veiling all that may befall_fallen-fell

不确定如何启动。

以下PCRE正则表达式应该可以工作:

match \b(\S+)\b(.*\n.*\b\1)$
replace by \2
flags : [m]ulti-line and [g]lobal
或者,在python中:

re.sub(r'\b(\S+)\b(.*\n.*\b\1)$', r'\2', here_text, flags=re.M)
你可以穿上或戴上试试

请注意,最后一个单词在前一行中被删除的行将不会再次匹配:

a
b a
b
将被替换为

 
b a
b
而不是

 
a
b

最后一个字在前一行中出现的次数是否总是相同的?我不明白输入是如何变成输出的。请详细解释一下。不,我只是想once@Arif哦,是的,我以为这就是你需要的。我会更新我的答案,并以另一条评论通知你。您可能还想更新您的问题,因为您只指定了“最后一个单词”,这听起来像是文本的最后一个单词,而不是行。@Arif已更新,但不处理空行删除。我建议你分开做,因为我认为在这个正则表达式中没有一个干净的方法来做它。@Arif我还添加了一个注释,你应该看看你是否没有。这个问题在正则表达式中无法解决,您需要在再次匹配之前将正则表达式引擎的指针重置为最后一个匹配行的开头,以解决它。当然可以,但是如果你在同一个正则表达式中不需要的话,我就不谈细节了。如果最后一个词以lough-laugh\u laugh fades/ends等结尾,我怎么能忽略它。在这种情况下,我想忽略“fades”或“ends”,只寻找“lough-laugh\u laugh”。@Arif标准是什么?至少包含一个破折号和一个下划线?
 
a
b