I'm trying to make a syntax highlighter for Python using regular expressions (in Python). Among other things, I want to highlight keywords such as for, while, if
etc. To do this I need a regex which matches them.
My issue is that I don't want, for instance, for
to be matched when it is inside a string, only when isolated (whitespace before and after).
I had \bfor\b
at first, which matches every occurrence of a separated for
. The issue with this is that it includes things like "string with for inside"
I have thought about look-behind/ahead (as this question suggests), but can't get around that this requires fixed width patterns in Python. Would love to get some guiding tips on things to try here.
In short: What could be a regex matching keywords such as for
only when interpreted by Python as such.