【问题标题】:Regex (python) to match same group several times only when preceded or followed by specific pattern正则表达式(python)仅在特定模式之前或之后匹配同一组多次
【发布时间】:2022-01-03 16:31:30
【问题描述】:

假设我有以下文本:

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

我需要匹配 «» 引号内的每个字符串,但仅限于以“要销毁的产品:”模式开头或以 (Rule) 模式结尾的时段内。

换句话说,在这个例子中,我不想匹配 Dilora 或 Apple。

获取捕获组中引用内容的正则表达式为:

«(.+?)»

是否可以将其“锚定”到以下模式(例如 Rule)甚至先前的模式(例如“要销毁的产品:”?

这是我在 regex101 上的saved attempt

非常感谢。

【问题讨论】:

  • 使用Products to be destroyed:\s*(«[^«»]*»(?:[\s,]+«[^«»]*»)*) 提取然后拆分以获得您需要的块或使用您当前的正则表达式提取引号内的所有块。
  • @WiktorStribiżew 是否需要(?<=Products to be destroyed: )(«[^«»]*»(?:[\s,]+«[^«»]*»)*)|(«[^«»]*»(?:[\s,]+«[^«»]*»)*)(?= \(Rule) 来说明“在以“要销毁的产品:”模式以(规则)模式结束的时期内。 "

标签: python regex


【解决方案1】:

您可以匹配箭头之间的至少一个部分,当匹配时,使用 re.findall 提取所有部分。

示例数据似乎在一个点内。在这种情况下,您可以使用否定字符类匹配至少一个匹配除点以外的任何字符的单个箭头部分。

Regex demo 至少匹配一次,another demo 匹配之后的单独部分

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

输出

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

【讨论】:

  • 这是否说明了“或以(规则)模式结尾”?
  • @MonkeyZeus 我不知道规则是什么,它也可能是它之前的点或字符串?如果是\(Rule\)就好了
  • 我理解为字符串“(Rule)”的存在
  • @MonkeyZeus 你可以这样写\bProducts to be destroyed:(?:(?!\(Rule\)).)*?«[^«»]*».*?\(Rule\)regex101.com/r/KOkY80/1你也可以发布你的解决方案。
  • 非常感谢。将研究以了解其工作原理:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多