0

I am working in Python 3 and i am a bit confused about negative lookahead.
When i use regex pattern (?!123)ABC, do i understand it right if i say that i am looking for a string 'ABC' but only if it does NOT continue with '123'?
CODE:

import re
print(re.search(r'(?!123)ABC', "ABC123"))

>>><_sre.SRE_Match object; span=(0, 3), match='ABC'>

Question here is, why is 'ABC' matched even if it continues with '123'?
This is just an example code, i am trying to understand the logic here.
Thank you for any explanation!

SevO
  • 303
  • 2
  • 11
  • `(?!123)ABC` matches an `ABC` that is not equal to `123` => it matches any `ABC`. – Wiktor Stribiżew May 09 '17 at 13:17
  • You should probably move the lookahead to the end for what you are trying to do, like this: `ABC(?!123)`. Demo here: https://regex101.com/r/Wyk2D3/1/ – degant May 09 '17 at 13:19
  • I would also add that `ABC(?!123)` is the regex that would match the string ABC only if it is not followed by 123. The position of lookahead is important ! `(?!123)ABC` actually means that, if what's follow this position is not 123, then try to match ABC from this same position. – Gawil May 09 '17 at 13:20
  • @degant: There is no solution asked for here, just a regex explanation request. SevO: see [this answer of mine](http://stackoverflow.com/questions/31201690/find-word-not-followed-by/31201710#31201710) explaining how negative lookaheads work. – Wiktor Stribiżew May 09 '17 at 13:21
  • You are saying: After you look at my expression ABC, check starting from the point where the look ahead is located, so in this case just before A in ABC, if the expression is not equal 123 (and it's not, because it's ABC). – Xyzk May 09 '17 at 13:22
  • I understand that @WiktorStribiżew, which is why I _did not post an answer_ but a comment instead. Just wanted to point out to the OP, that he is probably using it incorrectly. – degant May 09 '17 at 13:23
  • Your comments gave me answer, what i was looking for, that in lookarounds is position important. So i have a little mistake in my studying materials. Your comments helped a lot, thank you. – SevO May 09 '17 at 13:28
  • When you have a problem understanding basic regex patterns, it is quite enough reading stuff at http://regular-expressions.info. Also, see http://www.rexegg.com/regex-lookarounds.html - this is also a great site. – Wiktor Stribiżew May 09 '17 at 13:33

0 Answers0