簡體   English   中英

正則表達式(python)僅在特定模式之前或之后匹配同一組多次

[英]Regex (python) to match same group several times only when preceded or followed by specific pattern

假設我有以下文本:

Products to be destroyed: «Prabo», «Palox 2000», «Remadon strong» (Rule). The customers «Dilora» and «Apple» has to be notified.

我需要匹配«»引號內的每個字符串,但僅在以“要銷毀的產品:”模式開頭或以(規則)模式結尾的時段內。

換句話說,在這個例子中,我不想匹配 Dilora 或 Apple。

獲取捕獲組中引用的內容的正則表達式是:

«(.+?)»

是否可以將其“錨定”到以下模式(例如規則)甚至先前的模式(例如“要銷毀的產品:”?

這是我在 regex101 上保存的嘗試

非常感謝。

您可以在箭頭之間至少匹配一個部分,當匹配時,使用 re.findall 提取所有部分。

示例數據似乎在一個點內。 在這種情況下,您可以使用否定字符 class 匹配至少一個匹配除點之外的任何字符的單個箭頭部分。

至少一個匹配的正則表達式演示,以及隨后匹配單獨部分的另一個演示

import re

regex = r"\bProducts to be destroyed:[^.]*«[^«»]*»[^.]*\."
s = 'Products to be destroyed: «Prabo», «Palox 2000», «Remadon strong» (Rule). The customers «Dilora» and «Apple» has to be notified.'
result = re.search(regex, s)

if result:
    print(re.findall(r"«([^«»]*)»", result.group()))

Output

['Prabo', 'Palox 2000', 'Remadon strong']

暫無
暫無

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

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