前瞻行为

Lookahead Behaviour

如何使前瞻非贪婪?我希望第一种情况不匹配任何东西(如第二种情况),但它 returns "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)

前瞻应用于 winnie|bear(?= bear|pooh) 中的 bear 而不是 winnie。如果您希望它应用于两者,请使用

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

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

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