On this page:
9.9.1 Lookahead
9.9.2 Lookbehind

9.9 Looking Ahead and Behind🔗

你可以在模式中使用断言来向前或向后查看, 以确保子模式出现或不出现。这些 “环视” 断言由将待检查的子模式放入一个分组中来指定, 分组的前导字符为:?=(正向前瞻)、 ?!(负向前瞻)、?<=(正向后顾)、 ?<!(负向后顾)。请注意,断言中的子模式 不会在最终结果中产生匹配;它仅仅允许或禁止 其余部分的匹配。

9.9.1 Lookahead🔗

使用 ?= 的正向前瞻向前查看,确保 其子模式 可能 匹配。

> (regexp-match-positions #rx"grey(?=hound)"
    "i left my grey socks at the greyhound")

'((28 . 32))

regexp #rx"grey(?=hound)" 匹配 grey,但 仅当 它后跟 hound 时。因此, 文本字符串中第一个 grey 不被匹配。

使用 ?! 的负向前瞻向前查看,确保其 子模式 不可能 匹配。

> (regexp-match-positions #rx"grey(?!hound)"
    "the gray greyhound ate the grey socks")

'((27 . 31))

regexp #rx"grey(?!hound)" 匹配 grey,但 仅当它后面 不是 hound 时。因此 socks 前面的 grey 被匹配。

9.9.2 Lookbehind🔗

使用 ?<= 的正向后顾检查其子模式 可能 在文本字符串当前位置的紧左侧匹配。

> (regexp-match-positions #rx"(?<=grey)hound"
    "the hound in the picture is not a greyhound")

'((38 . 43))

regexp #rx"(?<=grey)hound" 匹配 hound,但 仅当它前面是 grey 时。

使用 ?<! 的负向后顾检查其子模式 不可能在紧左侧匹配。

> (regexp-match-positions #rx"(?<!grey)hound"
    "the greyhound in the picture is not a hound")

'((38 . 43))

regexp #rx"(?<!grey)hound" 匹配 hound,但 仅当它前面 不是 grey 时。

前瞻和后顾在不令人困惑时可以很方便。