0

I get this:

import re; 
print re.findall(r"q(?=u)", "qqq queen quick qeel")
> ['q', 'q'] # for queen and quick

But I don't get this:

import re; 
print re.findall(r"q(?!=u)", "qqq queen quick qeel")
> ['q', 'q', 'q', 'q', 'q', 'q'] # every q matches

I expected only 4 qs to match because the negative lookahead should see that in the word qeel for example, the letter after the q is not u.

What gives?

Nick Lang
  • 469
  • 6
  • 16

1 Answers1

2

It is

import re 
print(re.findall(r"q(?!u)", "qqq queen quick qeel"))
#                  ---^---
# ['q', 'q', 'q', 'q']


Without the =, that is. Otherwise, you don't want to have =u in front which is true for all of your qs here. In general, a positive lookahead is formed via (?=...) whereas a negative one is just (?!...).

Sidenote: the ; is not needed at the end of the line unless you want to write everything in one line which is not considered "Pythonic" but totally valid:
import re; print(re.findall(r"q(?!u)", "qqq queen quick qeel"))
Jan
  • 42,290
  • 8
  • 54
  • 79