正则表达式先行,后向和原子组 [英] 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)
您也可以将它们组合在一起:
You can also combine them:
(?<=foo)bar(?=bar) finds the 1st bar ("bar" with "foo" before it and "bar" after it)
定义
向前看肯定(?=)
在表达式B后面找到表达式A:
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
回避否定的(?<!)
查找表达式A,其中表达式B不在前面
Look behind negative (?<!)
Find expression A where expression B does not precede:
(?<!B)A
原子组(?>)
一个原子组退出一个组,并在该组内 first 匹配模式之后丢弃其他模式(禁用回溯功能).
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.
- http://www.regular-expressions.info/lookaround.html
- http://www.rexegg.com/regex-lookarounds.html
这篇关于正则表达式先行,后向和原子组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!