【问题标题】:issue with negative lookahead in python regexppython regexp中的负前瞻问题
【发布时间】:2015-03-07 22:49:18
【问题描述】:

我的正则表达式中的负前瞻被忽略了。我的语法不正确吗?

number_with_no_trailing_tag = re.compile(r"(\[number\sraw\='.+?'\])(?!\s\[)")

strings = [
    "[oper raw='+'] [number raw='9.8'] [units raw='m']",
    "foo [number raw='9.8'] bar",
    "[number raw='9.8'] bar",
    "foo [number raw='9.8']",
    "[number raw='9.8']",
    "[oper raw='+'] [number raw='9.8']",
    "[number raw='9.8'] [units raw='m']"]

matches = [number_with_no_trailing_tag.search(st) for st in strings]

for match in matches:
    if match is not None:
        print match.groups()

我的输出是:

("[number raw='9.8'] [units raw='m']",)
("[number raw='9.8']",)
("[number raw='9.8']",)
("[number raw='9.8']",)
("[number raw='9.8']",)
("[number raw='9.8']",)
("[number raw='9.8'] [units raw='m']",)

匹配所有的字符串,而我只希望得到字符串[1:6]的匹配。我的预期输出将是:

("[number raw='9.8']",)
("[number raw='9.8']",)
("[number raw='9.8']",)
("[number raw='9.8']",)
("[number raw='9.8']",)

什么给了?任何帮助将不胜感激。

【问题讨论】:

  • 你期望得到什么?
  • 抱歉,我发布了我的输出,但不是我的预期输出。不过现在已经解决了。谢谢你提醒我编辑

标签: python regex python-2.7 negative-lookahead


【解决方案1】:

您需要将.+? 部分更改为否定字符类...

re.compile(r"(\[number\sraw='[^']+'])(?!\s\[)")

eval.in

【讨论】:

  • 谢谢。解决了它。终于我实现了我的终极目标:number_with_no_adjacent_tags = re.compile(r"(?<!\]\s)(\[number\sraw\='[^']+'\])(?!\s\[)")
  • 哦,谢谢你把我指向 eval.in 我一直想要这样的东西,因为你不能在 jsbin 等中准确地发布 node.js 代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-03
  • 1970-01-01
  • 2018-09-06
  • 1970-01-01
  • 1970-01-01
  • 2021-11-09
相关资源
最近更新 更多