正则表达式前瞻、后视和原子组 [英] Regex lookahead, lookbehind and atomic groups
问题描述
我在我的正则表达式正文中发现了这些东西,但我不知道我可以用它们做什么.有人提供示例以便我尝试了解它们的工作原理吗?
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).
- 应用于
(?>foo|foot)s
将匹配它的第一个替代foo
,然后作为s 失败
不会立即跟随,因为回溯被禁用而停止
foots
的 (?>foo|foot)s
applied tofoots
will match its 1st alternativefoo
, then fail ass
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
将:
- 匹配它的第一个选择
foo
,然后失败,因为s
没有立即跟随在foots
中,并回溯到它的第二个选择;莉> - 匹配它的第二个选择
foot
,然后在foots
中紧跟在s
之后成功,然后停止.
- match its 1st alternative
foo
, then fail ass
does not immediately follow infoots
, and backtrack to its 2nd alternative; - match its 2nd alternative
foot
, then succeed ass
immediately follows infoots
, and stop.
这篇关于正则表达式前瞻、后视和原子组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!