使用 re.compile 识别文本文件的正确行

Identifying the correct line of a text file using re.compile

我是使用 Python 处理文本文件的新手,但我一直无法在文本文件中找到正确的行。

查看图像,我需要找到一种方法,块 returns 对我来说包含单词的行:

'收到新数据包' + 介于两者之间 + 变量stcrouter_line中存储的字符串。 (见图)。

就变量而言,returns3行,之前是正确的。现在,我只需要获取第二行(上面的模式)。

我想我需要在块的第一行正确表达:

line_regex = re.compile(stcrouter_line).

我不确定如何表述。有谁能帮帮我吗?

尝试将您的代码修改为:

line_regex = re.compile('New packet was received' + r'.*?' + stcrouter_line)

这是为了匹配:

  • New packet was received 按字面匹配文本
  • r'.*? 包含正则表达式 .*? 的原始字符串将匹配任何 上面的文字字符串和您现有的模式之间的文本。 在 * 之后使用 ? 使其成为最短匹配,以便匹配 不会超过您现有的模式。
  • stcrouter_line 你现有的模式