Python 正则表达式 : User Inputs Multiple Search Terms

标签 python regex search user-input

我的代码要做的是接收用户输入的搜索词,然后迭代 TCP 转储文件并按数据包查找该词的每个实例。 src IP 充当我输出中每个数据包的 header 。

所以我遇到了一个问题,当 fileIn 迭代第一个术语时,它似乎被删除了。因此,当程序查看第二个用户输入的搜索词时,它显然找不到任何内容。这是我所拥有的:

import re
searchTerms = []

fileIn = open('ascii_dump.txt', 'r')

while True:
    userTerm = input("Enter the search terms (End to stop): ")
    if userTerm == 'End':
        break
    else:
        searchTerms.append(userTerm)

ipPattern = re.compile(r'((?:\d{1,3}\.){3}\d{1,3})')

x = 0

while True:
    print("Search Term is:", searchTerms[x])
    for line in fileIn:
        ipMatch = ipPattern.search(line)
        userPattern = re.compile(searchTerms[x])
        userMatch = userPattern.search(line)

        if ipMatch is not None:
            print(ipMatch.group())

        if userMatch is not None:
            print(userMatch.group())
    x += 1
    if x >= len(searchTerms):
       break

最佳答案

发生这种情况是因为您将文件对象作为迭代器打开,该迭代器在第一次通过 for 循环中被消耗。

在第二次循环期间,for line in fileIn 将不会被计算,因为迭代器 fileIn 已被消耗。

一个快速解决方法是执行以下操作:

lines = open('ascii_dump.txt', 'r').readlines()

然后在 for 循环中,将 fileIn 中的 for 行更改为:

for line in lines:

话虽如此,您应该重写代码,以便使用正则表达式或运算符在一次传递中完成所有正则表达式匹配。

关于Python 正则表达式 : User Inputs Multiple Search Terms,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26850392/

相关文章:

python - 删除紧邻单词之前的数字

python - 如何在 Python 中使用正则表达式从字符串中提取数字,除非在括号内?

php - 用 PHP 搜索 MySQL

Python 花旗骰 : Creating a list with sets. 意外类型

python - 组合不同列表中的项目,python

Python 两个列表之间的多重条件

regex - 在带有括号的一维列表上应用递归

php - 站点地图 xml 文件; url 是否必须以 ".htm"结尾?

c - 使用字符串作为数组索引标识符(无循环)

python - 尝试在Python脚本中复制文件,但不起作用