python - 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”这样的行在评论中
解决方案
这可以通过可变长度的否定后向断言来完成,但为此您需要使用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='')
推荐阅读
- guice - 如何绑定动态@Named 绑定
- abap - 形参个数大于实参个数
- javascript - 在角度项目中的数组上设置间隔
- python - 在 localhost 打开但永远保持空白的地方使用 vpython 时出现问题
- scala - Scala 跨项目中的资源
- django - 如何在 django 查询中将表单中的日期与 db 中的日期进行比较?
- django - 在具有嵌套资源的 Tastypie 中,对于给定的 url,获取视图函数名称的最佳方法是什么?
- php - Yii:尽管安装了 memcache/memcached,CMemCache 仍需要加载 PHP memcache 扩展
- python - Python pkg_resources 找不到模块
- postgresql - INSERT 到只有一个串行列的表实际上并没有插入任何东西