【问题标题】:How to exclude part of alternative from capture?如何从捕获中排除部分替代方案?
【发布时间】:2015-06-25 19:19:39
【问题描述】:

有一个正则表达式:((?:description|speed|type|peers)\s+set|classify)。 如何从捕获组中排除\s+set

必须只有descriptionspeedtypepeersclassify

我们可以这样做:

pattern = '^\s+"([A-Za-z]+)\.([_A-Za-z0-9-]+)"\s+"([^\s]+)"\s+((description|speed|type|peers)\s+set|classify)\s+"?(.+)"?'
p = re.compile(pattern)
path = 'some_file'
fd = open(path)
for l in fd.readlines():
    m = p.search(l)
    if not m:
        continue
    g = m.groups()
    if g[4]:
        (region, host, interface, cmd, value) = g[0].lower(), g[1].lower(), g[2].lower(), g[4], g[5]
    else:
        (region, host, interface, cmd, value) = g[0].lower(), g[1].lower(), g[2].lower(), g[3], g[5]

但它很丑......

if g[4]:
    (region, host, interface, cmd, value) = g[0].lower(), g[1].lower(), g[2].lower(), g[4], g[5]
else:
    (region, host, interface, cmd, value) = g[0].lower(), g[1].lower(), g[2].lower(), g[3], g[5]

如何使用正则表达式引擎剪切\s+set,并且代码中只有一行:

(region, host, interface, cmd, value) = g[0].lower(), g[1].lower(), g[2].lower(), g[3], g[4] ?

【问题讨论】:

  • 您是否尝试过使用环视?
  • 嗨。我尝试使用 ^\s+"([A-Za-z]+)\.([_A-Za-z0-9-]+)"\s+"([^\s]+)"\s+((说明|speed|type|peers)(?=\s+set)|classify)\s+"?(.+)"?'
  • 但 'set' 属于最后一组...
  • 我建议你使用类似regex101.com/#python 的东西来帮助你发展你的表达方式。您也可以考虑在一大步中尝试少做一些事情。

标签: python regex python-2.7 pcre regular-language


【解决方案1】:

如果您不介意多个捕获组(并因此稍微修改其余代码),这非常容易 - 只需执行与您正在做的相反的操作即可。

(?:(description|speed|type|peers)\s+set|(classify))https://regex101.com/r/bR1nV7/1 所示

如果您不想要它,您可以使用环视。 ((?:description|speed|type|peers)(?=\s+set)|classify) 如在 https://regex101.com/r/bR1nV7/2 中看到的

正则表达式中没有“排除这个东西”,因为其他工具(如非捕获组和环视)可以为您完成。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多