【问题标题】:How do I capture the text between curly brackets with a specific pattern inside of those curly brackets如何在大括号内捕获具有特定模式的大括号之间的文本
【发布时间】:2019-10-09 22:01:53
【问题描述】:

如果部分字符匹配,我正在尝试捕获大括号(包括大括号)之间的字符。

我尝试了下面的正则表达式模式,但它会抓取从整个字符串中的第一个大括号和最后一个大括号开始的所有内容。

string = "The {name_of_list} list contains {list:a, b, and c}. This list should be formatted as a, b, and c."

r"(\{.*?:a, b, and c\})"gm

我想捕获“{list:a, b, and c}”,但我得到的是“{name_of_list} list contains {list:a, b, and c}”。

【问题讨论】:

  • .*? 替换为[^{}]*?. 匹配除换行符以外的任何字符,这就是原因。
  • 试试r"(\{.+?\})"

标签: python regex


【解决方案1】:

. 模式匹配除换行符以外的任何字符,这就是您得到意外结果的原因。

要使其符合您的需要,您需要“调整”点,在这里,最好使用否定字符类,[^{](除{ 之外的任何字符)或[^{}](任何字符但是{}):

import re
s = "The {name_of_list} list contains {list:a, b, and c}. This list should be formatted as a, b, and c."
print(re.findall(r'\{[^{}]*?:a, b, and c}', s))

查看regex demoPython demo

要匹配包含: 的花括号内的任何字符串,您可以使用

r'\{[^{}:]*:[^{}]*}'

查看包含在第一个否定字符类中的:,它让我们可以使用贪婪的* 量词来提高效率。

【讨论】:

  • r'{[^}]*:a, b, and c}'(没有?)似乎也有效?
  • @Dino 是的,我假设计划是 1)只匹配没有 {} 的子字符串,2): 之前的字符串比它之后的部分短(然后惰性量词更有效)。如果第二部分更短,我会使用贪婪的量词。
  • 啊!我从没想过效率。感谢您的澄清!
  • 这行得通。谢谢!仅供参考,我最终通过使用模式\{[^{}:]*:a, b, and c[^{}]*} 构建了您推荐的内容。这是因为我需要单独捕获{list: a, b and c}(上面的代码中没有显示),这与{list: a, b, and c}不同。
猜你喜欢
  • 1970-01-01
  • 2019-03-18
  • 1970-01-01
  • 2021-04-27
  • 2017-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-10
相关资源
最近更新 更多