正则表达式前瞻、后视和原子组 [英] Regex lookahead, lookbehind and atomic groups

查看:38
本文介绍了正则表达式前瞻、后视和原子组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的正则表达式正文中发现了这些东西,但我不知道我可以用它们做什么.有人提供示例以便我尝试了解它们的工作原理吗?

I found these things in my regex body but I haven't got a clue what I can use them for. Does somebody have examples so I can try to understand how they work?

(?!) - 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)

定义

向前看积极(?=)

找到表达式 A,其中表达式 B 跟随:

Definitions

Look ahead positive (?=)

Find expression A where expression B follows:

A(?=B)

向前看否定(?!)

找到表达式 A,其中表达式 B 不跟随:

Look ahead negative (?!)

Find expression A where expression B does not follow:

A(?!B)

看后面正(?<=)

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

Look behind positive (?<=)

Find expression A where expression B precedes:

(?<=B)A

看后面的否定(?<!)

找到表达式 B 不在前面的表达式 A:

Look behind negative (?<!)

Find expression A where expression B does not precede:

(?<!B)A

原子团(?>)

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

Atomic groups (?>)

An atomic group exits a group and throws away alternative patterns after the first matched pattern inside the group (backtracking is disabled).

    应用于 foots
  • (?>foo|foot)s 将匹配它的第一个替代 foo,然后作为 s 失败 不会立即跟随,因为回溯被禁用而停止
  • (?>foo|foot)s applied to foots will match its 1st alternative foo, then fail as s does not immediately follow, and stop as backtracking is disabled

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

A non-atomic group will allow backtracking; if subsequent matching ahead fails, it will backtrack and use alternative patterns until a match for the entire expression is found or all possibilities are exhausted.

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

  1. 匹配它的第一个选择 foo,然后失败,因为 s 没有立即跟随在 foots 中,并回溯到它的第二个选择;
  2. 匹配它的第二个选择 foot,然后在 foots 中紧跟在 s 之后成功,然后停止.
  1. match its 1st alternative foo, then fail as s does not immediately follow in foots, and backtrack to its 2nd alternative;
  2. match its 2nd alternative foot, then succeed as s immediately follows in foots, and stop.

这篇关于正则表达式前瞻、后视和原子组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆