【问题标题】:Non greedy regex within parenthesis and contains text括号内的非贪婪正则表达式并包含文本
【发布时间】:2018-06-06 21:44:35
【问题描述】:

假设我有一个看起来像这样的字符串

test = 'this is a (meh) sentence that uses (random bits of meh2) and (this is silly)'

如果括号内包含单词“meh”,我只想提取文本。

执行常规的非贪婪正则表达式以匹配括号内的任何内容:

re.findall(r'\((.*?)\)', test)

返回

['meh', 'random bits of meh2', 'this is silly']

尝试这样做只包含第一个和第二个内容:

re.findall(r'\((.*meh.*?)\)', test)

返回

['meh) sentence that uses (random bits of meh2']

我想要一个正则表达式只返回

['meh', 'random bits of meh2']

有人可以帮忙吗?谢谢!

【问题讨论】:

  • 使第一个 .* 不贪婪。
  • ^yup: \((.*?meh.*?)\)
  • 啊,错过了那个。谢谢!

标签: python regex python-3.x


【解决方案1】:

您可以使用[^\)](现在是.)来允许除右括号之外的所有字符。

re.findall(r'\(([^\)]*meh[^\)]*?)\)', test)

【讨论】:

  • 有趣的是,比较 regex101.com 上的两个选项,这个版本在 ~4ms 时使用了 131 步,而非贪婪版本在 ~1ms 时使用了 146 步。
【解决方案2】:
re.findall(r'\((.*?meh.*?)\)', test)

【讨论】:

  • r'\((.*?meh.*?)\)' 不起作用。应该是re.findall(r'\(([^()]*meh[^()]*)\)', test)
  • 不鼓励使用纯代码的答案。您能否描述一下为什么 OP 的代码不起作用,以及这可能起作用的区别是什么?
  • @WiktorStribiżew - 为什么非贪婪不起作用?我一直更喜欢[^()] 方法,因为它感觉更......明确,但我想不出任何可以打破非贪婪的具体例子。
  • @zzxyz 与this is a (meh) sentence that uses (random bits of meh2) and (this is silly),只是巧合\((.*?meh.*?)\) 有效。你can see it breaks with (this) is a (meeeeeh) sentence that uses (random bits of meh2) and (this is silly) already.
  • @WiktorStribiżew - 啊是的......懒惰,但正则表达式尽快开始。谢谢!
猜你喜欢
  • 2011-08-29
  • 1970-01-01
  • 2016-12-14
  • 1970-01-01
  • 1970-01-01
  • 2013-02-15
  • 1970-01-01
  • 2011-04-27
  • 2010-10-20
相关资源
最近更新 更多