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

2024-04-20 12:41:57 发布

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

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

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
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

不知道怎么开始。你知道吗


Tags: andwithlinesoftclosingroundlaughfell
1条回答
网友
1楼 · 发布于 2024-04-20 12:41:57

以下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)

你可以在regex101ideone上试试。你知道吗

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

a
b a
b

将被替换为

 
b a
b

而不是

 
a
b

相关问题 更多 >