【问题标题】:How can I properly handle greedy and optional patterns in python regex如何正确处理 python regex 中的贪婪和可选模式
【发布时间】:2013-06-11 18:53:42
【问题描述】:

我有一个包含路径的变量,我想从路径中提取第 6 个文件夹,但第 7 个文件夹可能会出现也可能不会出现。在这两种情况下......正则表达式应该返回“三”,但第一个示例无法匹配。我试过用?表示可选,但我的尝试不正确。

我需要在正则表达式中进行哪些更改以使其在两种情况下都匹配:

path = "//network/path/folder/_one/two/three"  # fails 
path = "//network/path/folder/_one/two/three/four"  # works

p = re.compile('^//network/path/folder/_.*?/.*?/(.*?)/')   # compile the regex
m = re.search(p, path)    # regex search

if m:     # regex matched
    print "6th folder =",m.group(1)

【问题讨论】:

  • path.split('/')[7] 有什么问题 -> 'three'?

标签: python regex non-greedy


【解决方案1】:

也许您可以针对较小的字符而不是 .*

^//network/path/folder/_.*?/[^/]*/([^/]*)

http://regexr.com?356lh

[^/]* 表示任何字符出现的任意次数,但不是正斜杠。 ^ 不是标志。

【讨论】:

  • 那行得通,但是 [^/]* 是什么意思...它是否意味着匹配除 / 之外的所有字符
猜你喜欢
  • 2012-11-17
  • 1970-01-01
  • 1970-01-01
  • 2020-03-15
  • 1970-01-01
  • 1970-01-01
  • 2010-10-20
相关资源
最近更新 更多