The difference in the match due to the position of the negative look?

I have a lot of confusion in regex and am trying to solve them. Here I have the following line:

{start}do or die{end}extended string 

My two different regular expressions, where I just repositioned the point:

 (.(?!{end}))* //returns: {start}do or di //^ See here ((?!{end}).)* //returns: {start}do or die //^ See here 

Why does the first regular expression eat the last "e"?

And also how does this negative look make this quantifier not greedy? I mean, why can't it consume characters outside of {end}?

+7
javascript string php regex lookahead
source share
2 answers

With your negative look you say that it is impossible to combine a regular expression, which in your case is {end} . And . captures everything except a new line.

So, with your first regex:

 (.(?!{end}))* 

It does not matter e , because: e{end} cannot match due to its negative appearance. Whereas in the second regex, where you have a dot on the other side, it can until: {end}d , so e will be included in the second regex.

+2
source share

I calculated the regex workflow for regex when doing the task ...

First, for the (.(?!{end}))* approach for the regex engine as follows:

 "{start}do or die{end}extended string" ^ .(dot) matches "{" and {end} tries to match here but fails.So "{" included "{start}do or die{end}extended string" ^ . (dot) matches "s" and {end} tries to match here but fails.So "s" included .... ....so on... "{start}do or die{end}extended string" ^ (dot) matches "e" and {end} here matches "{end}" so "e" is excluded.. so the match we get is "{start}do or di" 

for the regular expression secodn ((?! {end}).) * ....

 "{start}do or die{end}extended string" ^ {end} regex tries to match here but fails to match.So dot consumes "{". "{start}do or die{end}extended string" ^ {end} regex tries to match here but fails again.So dot consumes "s". .... ..so on.. "{start}do or die{end}extended string" ^ {end} regex tries to match here but fails.So dot consumes the "e" "{start}do or die{end}extended string" ^ {end} regex tries to match here and succeed.So the whole regex fail here. So we ended up with a match which is "{start}do or die" 
+1
source share

All Articles