Understanding negative lookahead

喜夏-厌秋 提交于 2019-11-27 22:39:50
nu11p01n73R

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

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

How a(?!b)c matches ac

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.

E.g.

abc(?=123)\d+ matching 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 

@Antario, I was confused about the negative look ahead/behind case in regex for a while and this site has a great explanation.

So with your example what you are saying is that you have a literal "a" and it is NOT followed by a literal "b" and it IS followed by a literal "c".

Here is a different regex debugger than you used which gives a more visual answer which personally I find helpful :)

a(?!b)c

Debuggex Demo

a(?!b)c will match only ac because the only way you'll have an a followed by "not b" (which will not be consumed) and then c, is ac.

So, in that case the regex matches any string that contains strictly 3 characters and is not the abc

This is not quite right. This regex states that we are searching a sequence which firstsymbol is a and after that is c, and inside there is no b.

For example, a(?!b). will match either ac or af as there is no restrictions on the last symbol via .

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!