gpt4 book ai didi

正则表达式前瞻、后瞻和原子组

转载 作者:太空宇宙 更新时间:2023-11-04 11:58:06 30 4
gpt4 key购买 nike

我在我的正则表达式体内发现了这些东西,但我不知道我可以用它们做什么。有人有例子以便我可以尝试理解它们是如何工作的吗?

(?!) - negative lookahead
(?=) - positive lookahead
(?<=) - positive lookbehind
(?<!) - negative lookbehind

(?>) - atomic group

最佳答案

示例

给定字符串 foobarbarfoo :

bar(?=bar)     finds the 1st bar ("bar" which has "bar" after it)
bar(?!bar) finds the 2nd bar ("bar" which does not have "bar" after it)
(?<=foo)bar finds the 1st bar ("bar" which has "foo" before it)
(?<!foo)bar finds the 2nd bar ("bar" which does not have "foo" before it)

您还可以将它们组合起来:

(?<=foo)bar(?=bar)    finds the 1st bar ("bar" with "foo" before it and "bar" after it)

定义

积极向前看 (?=)

在表达式 B 后面查找表达式 A:

A(?=B)

向前看负面(?!)

查找表达式 B 不跟随的表达式 A:

A(?!B)

看背后积极(?<=)

在表达式 B 之前查找表达式 A:

(?<=B)A

看看负面的背后(?<!)

查找表达式 B 不位于前面的表达式 A:

(?<!B)A

原子团 (?>)

原子组退出组并丢弃组内第一个匹配模式之后的替代模式(回溯被禁用)。

  • (?>foo|foot)s适用于foots将匹配其第一个替代方案 foo ,然后失败为 s不会立即跟随,并因回溯被禁用而停止

非原子组将允许回溯;如果后续匹配失败,它将回溯并使用替代模式,直到找到整个表达式的匹配或用尽所有可能性。

  • (foo|foot)s适用于foots将会:

    1. 匹配第一个替代方案 foo ,然后失败为 s不立即跟随 foots ,并回溯到第二个选择;
    2. 匹配其第二个替代方案 foot ,然后成功为 s紧接着foots ,然后停止。

一些资源

在线测试人员

关于正则表达式前瞻、后瞻和原子组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41181641/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com