首页 > 解决方案 > Python 使用 re.search 排除注释

问题描述

我正在使用以下方法在一行中搜索一个字符串:

import re

myfile = "myfile.txt"
files = open(myfile, 'r').read().splitlines()
for line in file:
    if re.search("`this", line):
        print "bingo"

这工作正常。但是,我想排除任何注释行。我正在从中读取行的文件中的注释可以具有//. 我不确定如何排除评论。注释可以从行中的任何位置开始,不一定在行首。

例子:

我想排除像first_last = "name" //`this THAT“`this”这样的行在评论中

标签: pythonregex

解决方案


这可以通过可变长度的否定后向断言来完成,但为此您需要使用regex可与存储库一起安装pip的包PyPi。正则表达式是:

(?<!//.*)    # negative lookahead assertion stating that the following must not be preceded by // followed by 0 or more arbitary characters
`this        # matches `this

编码:

import regex as re

regex = re.compile(r'(?<!//.*)`this')
myfile = "myfile.txt"
with open(myfile, 'r') as f:
    for line in f: # line has newline character at end; call rstrip method on line to get rid if you want
        if regex.search(line):
            print(line, end='')

正则表达式演示


推荐阅读