I want to match the string path
but not the string os.path
. How do I go about that ? Tried (?!(os\.path))\bpath\b
but I still get all os.path
S
Asked
Active
Viewed 164 times
0

Community
- 1
- 1

Mr_and_Mrs_D
- 32,208
- 39
- 178
- 361
-
`(?<!os\.)\bpath\b` ? – Sebastian Proske Oct 15 '16 at 13:30
-
@SebastianProske: seems to work - could you add an answer explaining why it works and how I can be sure it will mathc complex cases like `if path and not os.path.sep in path` for instance – Mr_and_Mrs_D Oct 15 '16 at 13:32
-
From the given string, do you want to match all occurences of path that are not connected to os. or none at all? – Sebastian Proske Oct 15 '16 at 13:33
-
I want all lines that contain the word path but not os.path only (or sys.path for that matter) so the line above should be a match – Mr_and_Mrs_D Oct 15 '16 at 13:35
2 Answers
1
You can use a look-behind based regex, like
(?<!os\.)\bpath\b
This basically matches the exact word path
and ensures that it is not preceded by os.
If you want to avoid similar constructs, like sys.path
or xx.path
you could use (?<!\w\.)
as look-behind instead.
See the regex101 demo.

Sebastian Proske
- 8,255
- 2
- 28
- 37
-
-
1Your lookebhind was starting at the same position, as your match started, thus directly in front of `path` - and thus would always be correct. You might check this with `(?!(os\.path))..\.\bpath\b`... – Sebastian Proske Oct 15 '16 at 13:45