【问题标题】:Lookahead Behaviour前瞻行为
【发布时间】:2015-06-14 16:49:32
【问题描述】:

如何使前瞻不贪婪?我希望第一种情况不匹配任何东西(如第二种情况),但它返回“winnie”。我猜是因为它在“the”之后贪婪匹配?

str <- "winnie the pooh bear"

## Unexpected
regmatches(str, gregexpr("winnie|bear(?= bear|pooh)", str, perl=T))
# [1] "winnie"

## Expected
regmatches(str, gregexpr("winnie(?= bear|pooh)", str, perl=T))
# character(0)

【问题讨论】:

    标签: regex r lookahead


    【解决方案1】:

    前瞻应用于winnie|bear(?= bear|pooh) 中的bear 而不是winnie。如果您希望它同时应用于两种用途

    (?:winnie|bear)(?= bear|pooh)
    

    现在它将适用于两者。 因为winnie 匹配ored part bear 从未出现过,也没有前瞻。

    在第二种情况下,lookahead 应用于winnie。所以它失败了。

    【讨论】:

    • 哦,还有很多 ✩ 点 ✪ 我现在看到了 ツ chai ☕ 在你的 50k 或 100k 生日肯定!
    猜你喜欢
    • 2020-07-03
    • 2012-07-22
    • 2019-02-08
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多