簡體   English   中英

Python-匹配最后一個單詞並從上一行刪除

[英]Python - match the last word and delete from previous line

我正在嘗試匹配最后一個單詞並從上一行刪除。

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

不知道如何開始。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM