【问题标题】:Python Exclude Comments with re.searchPython 使用 re.search 排除注释
【发布时间】:2020-04-01 03:56:53
【问题描述】:

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

import re

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

这很好用。但是,我想排除任何属于 cmets 的行。我正在从中读取行的文件中的 cmets 可以具有 // 形式的 cmets。我不确定如何排除 cmets。注释可以从行中的任何位置开始,不一定在行首。

例子:

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

【问题讨论】:

  • python 不支持// 评论
  • @AlwaysSunny 我的脚本在 python 中,但我正在阅读的文件不是。我正在阅读的文件有我提到的 cmets。
  • @Mandy8055 我在 python 正则表达式测试器上进行了测试,但这似乎不适用于 python。抛出错误。
  • @sfr 您不需要复制regex,因为它是为.net 语言编写的。请阅读this

标签: python regex


【解决方案1】:

这可以通过可变长度的否定后向断言来完成,但为此您需要使用可与pip 一起安装的regex 包,形成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='')

Regex Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    相关资源
    最近更新 更多