了解负面前瞻 [英] Understanding negative lookahead

查看:88
本文介绍了了解负面前瞻的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图了解负面的超前行为在简单示例中的工作方式.例如,考虑以下正则表达式:

I'm trying to understand how negative lookaheads work on simple examples. For instance, consider the following regex:

a(?!b)c

我认为否定的前瞻匹配一个职位.因此,在这种情况下,正则表达式匹配任何严格包含3个字符且不是abc的字符串.

I thought the negative lookahead matches a position. So, in that case the regex matches any string that contains strictly 3 characters and is not abc.

但这不是真的,正如 此演示 .为什么?

But it's not true, as can be seen in this demo. Why?

推荐答案

先行符不占用任何字符.它只是检查前瞻是否可以匹配:

Lookaheads do not consume any characters. It just checks if the lookahead can be matched or not:

a(?!b)c

因此在这里,在匹配a之后,它只是检查,如果它后面没有b,但不消耗该not字符(即c)并且后面是c.

So here after matching a it just checks if it is followed not by b but does not consume that not character (which is c) and is followed by c.

ac
|
a

ac
 |
(?!b) #checks but does not consume. Pointer remains at c

ac
 |
 c


正向超前

正面前瞻相似之处在于 尝试匹配前瞻中的模式 .如果可以匹配,则正则表达式引擎继续匹配其余模式.如果无法匹配,则该匹配项将被丢弃.


Positive lookahead

The positive lookahead is similar in that it tries to match the pattern in the lookahead. If it can be matched, then the regex engine proceeds with matching the rest of the pattern. If it cannot, the match is discarded.

例如

abc(?=123)\d+匹配abc123

abc123
|
a

abc123
 |
 b

abc123
  c

abc123 #Tries to match 123; since is successful, the pointer remains at c
    |
 (?=123)

abc123 # Match is success. Further matching of patterns (if any) would proceed from this position
  |

abc123
   |
  \d

abc123
    |
   \d

abc123 #Reaches the end of input. The pattern is matched completely. Returns a successfull match by the regex engine
     |
    \d

这篇关于了解负面前瞻的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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