-2

I'm a newbie here and would like to write a regex in Python to return True if the search keyword is found and it's NOT preceded by specific character/s.

Basically, would like to return True if it does NOT contain "--" anywhere before the specific search keyword since "--" denote comment in SQL syntax.

Ex:

s1 = "from tblEmployee e"
s2 = "--from tblEmployee e"
s3 = "from tblDepartment --tblEmployee e"
s4 = "from tblEmployee e --sample comment"

Given the scenario above if we're looking for "tbl_Employee" keyword, it will only return True for s1 and s4.

Is it possible?

Any suggestion would be appreciated.

Thanks!

Edit: Searching keyword should be exact match including the casing:

Ex:

s5 = "from tblEmployee1 e"
s6 = "from tblEmployee1"
s7 = "from TBLEmployee e"

s5, s6 and s7 will return False.

pren
  • 45
  • 2
  • 8

1 Answers1

2

Inverse matching is not completely trivial with regular expressions. You can do this, though:

import re

def kw_in_s(kw, s):
    pat = r'^((?!--).)*\b{}\b.*'.format(kw)
    return bool(re.match(pat, s))

# '(?!--)': negative look-ahead, matches only if not followed by '--'
# '((?!--).)*': zero or more characters none of which is followed by '--'
# '\b{}\b': keyword formatted between two word boundaries

>>> kw_in_s('tblEmployee', "--from tblEmployee e")
False
>>> kw_in_s('tblEmployee', "from tblEmployee e")
True
>>> kw_in_s('tblEmployee', "from tblDepartment --tblEmployee e")
False
>>> kw_in_s('tblEmployee', "from tblEmployee e --sample comment")
True
>>> kw_in_s('tblEmployee', "from tblDepartment tblEmployee1 e")
False

Python regular expression syntax docs.

user2390182
  • 72,016
  • 6
  • 67
  • 89
  • Thanks for the quick response! This works. But forget to mention that it should be exact match including casing: Example: This should return False. print kw_in_s('tblEmployee', "from tblEmployee1 e") – pren Feb 26 '17 at 07:22
  • Just passing through, but I really like your approach to this! – Regular Jo Feb 26 '17 at 08:24
  • @cfqueryparam Thx, but not really [original](http://stackoverflow.com/questions/6259443/how-to-match-a-line-not-containing-a-word) though ;) – user2390182 Feb 26 '17 at 08:33