在 python 的 re 模块中需要帮助

Need help in re module of python

我正在尝试使用 re 模块来解析文件。我尝试了三个版本的代码,前两个版本没有检索到任何 O/P。第三个版本只检索一行。有人可以看看吗? 版本 1:

import re
file = open('sample.txt', 'r') 
x = file.readline()
while x:
    var = re.findall(r'(?:\*|\*>)\s+(\d+.\d+.\d+.\d+\/\d+\s+)?(\S+)\s+\d+\s+(\d+\s+.+)[ie]',x)
    x = file.readline()
print(var)
file.close()

版本 2:

import re
file = open('sample.txt', 'r')
x = file.read()
var = re.findall(r'(?:\*|\*>)\s+(\d+.\d+.\d+.\d+\/\d+\s+)?(\S+)\s+\d+\s+(\d+\s+.+)[ie]',x)
print(var)
file.close()

版本 3:

import re
file = open('sample.txt', 'r') 
x = file.readline()
while x:
    var = re.search(r'(?:\*|\*>)\s+(\d+.\d+.\d+.\d+\/\d+\s+)?(\S+)\s+\d+\s+(\d+\s+.+)[ie]',x, re.M)
    x = file.readline()
print(var.group(0))
file.close()

sample.txt中的数据如下。第一行之后网络是空白的,当我 运行 单独 python shell 上的这些语句时,正则表达式正在工作。


                Oregon Exchange BGP Route Viewer
      route-views.oregon-ix.net / route-views.routeviews.org

该硬件是 NSF 资助的一部分。 如果您有任何问题,请联系 help@routeviews.org,或者 如果你想贡献你的观点。

 Network          Next Hop            Metric LocPrf Weight Path
 *   64.48.0.0/16     173.205.57.234                         0 53364 3257 2828 i

 *                    202.232.0.2                            0 2497 2828 i

 *                    93.104.209.174                         0 58901 51167 1299 2828 i

 *                    193.0.0.56                             0 3333 2828 i

 *                    103.197.104.1                          0 134708 3491 2828 i

 *                    132.198.255.253                        0 1351 6939 2828 i

我认为这可以解决问题:

import re

thelist = [
"*   64.48.0.0/16     173.205.57.234                         0 53364 3257 2828 i",
"*                    93.104.209.174                         0 58901 51167 1299 2828 i",
"*                    193.0.0.56                             0 3333 2828 i",
]

regex = re.compile("\*\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/\d{1,3})?\s+([\S]+)\s+([^i]+i)")

for text in thelist:
    match = re.search(regex, text)
    if match:
        print ("yuppers")
        print (match.group(1))
        print (match.group(2))
        print (match.group(3))
        print ("\n")
    else:
        print ("nope")

结果

yuppers
64.48.0.0/16
173.205.57.234
0 53364 3257 2828 i


yuppers
None
93.104.209.174
0 58901 51167 1299 2828 i


yuppers
None
193.0.0.56
0 3333 2828 i

根据您实际想要对每个结果执行的操作,您只需 fiddle 结果即可。正则表达式使网络成为可选的,这可能会让您感到困惑。希望这能让您朝着正确的方向前进!