Regular expression: match word not between quotes

后端 未结 5 448
不知归路
不知归路 2021-01-15 00:25

I would like a Python regular expression that matches a given word that\'s not between simple quotes. I\'ve tried to use the (?! ...) but without success.

5条回答
  •  旧时难觅i
    2021-01-15 00:35

    How about this regular expression:

    >>> s = '''var foe = 10;
    foe = "";
    dark_vador = 'bad guy'
    ' I\m your father, foe ! '
    bar = thingy + foe'''
    >>>
    >>> re.findall(r'(?!\'.*)foe(?!.*\')', s)
    ['foe', 'foe', 'foe']
    

    The trick here is to make sure the expression does not match any string with leading and trailing ' and to remember to account for the characters in between, thereafter .* in the re expression.

提交回复
热议问题