Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python正则表达式:用户输入多个搜索词_Python_Regex_Search_User Input - Fatal编程技术网

Python正则表达式:用户输入多个搜索词

Python正则表达式:用户输入多个搜索词,python,regex,search,user-input,Python,Regex,Search,User Input,我的代码要做的是接收用户输入的搜索词,然后遍历tcp转储文件,并按数据包查找该词的每个实例。src IP充当输出中每个数据包的报头 因此,我遇到了一个问题,当fileIn在第一个术语中迭代时,它似乎被删除了。因此,当程序查看第二个用户输入的搜索词时,它显然找不到任何东西。以下是我所拥有的: import re searchTerms = [] fileIn = open('ascii_dump.txt', 'r') while True: userTerm = input("Ente

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

因此,我遇到了一个问题,当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
您需要在fileIn循环中的
for行之后“倒带”文件:

...
fileIn.seek(0);
x += 1

之所以会出现这种情况,是因为您以迭代器的形式打开了文件对象,该迭代器在第一次通过
for
循环使用

在循环的第二次执行过程中,由于迭代器
fileIn
已被使用,因此不会对fileIn
中的行的
求值

一个快速解决方法是:

lines = open('ascii_dump.txt', 'r').readlines()
然后在
for
循环中,将
for line in fileIn
更改为:

for line in lines:

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

谢谢您的帮助。我的下一个问题是,我还需要显示找到的搜索词之前的前20个字符和搜索词之后的20个字符。对于正则表达式,我知道这是类似于:[.+]{20}\.VARIABLE\.[.+]{20}的。使用转义的“.”,因为这是tcp转储分离字符串的方式。如何
userPattern=re.compile(“.{20}\.%s\..{20}'%searchTerms[x])
Hey。事实证明,在%s之前或之后最多可以有20个,所以我只是在%s的每一侧添加了{0,20}。谢谢也谢谢你的帮助!这两种方法都发挥了作用。正如我在上面的评论中所提到的:“我的下一个问题是,我还需要显示找到的搜索词之前的前20个字符和搜索词之后的20个字符。对于正则表达式,我知道这将类似于:[.+]{20}\.VARIABLE\..+]{20}。使用转义的“.”,因为这是tcp转储分离字符串的方式。”。