nyxthulhu
nyxthulhu

Reputation: 9752

Backchecking on python regex

I'm trying to write a regular expression match

I'd like to match c99 in files, so long as its not part of a hexadecimal color code for example

Is this even possible with regex?

Upvotes: 1

Views: 127

Answers (3)

burning_LEGION
burning_LEGION

Reputation: 13450

use this regex (^([^#].*?)?c99.*?$)

Upvotes: 0

BrenBarn
BrenBarn

Reputation: 251408

Using the regex module:

>>> rx = regex.compile(r"(?<!#\d{0,3})c99")
>>> rx.findall("#000c99")
[]
>>> rx.findall("/mysite.com/c99.php")
[u'c99']
>>> rx.findall("%20c99.php")
[u'c99']
>>> rx.findall("c99?hi=moo")
[u'c99']

Upvotes: 2

user1502237
user1502237

Reputation:

The most straight forward way would be to match lines with "c99" in them then discard any where the c99 is in a color code:

line = fileHandle.readline()
while (line) :
     if (re.search("c99", line)) :
          if (re.search("#.?.?.?c99", line)) :
               pass
          else :
               # line contains c99 not in a color code
     line = fileHandle.readline()

There's probably a way to do it within a single regex, but this was just the first thing that came to mind.

Upvotes: 1

Related Questions