Python逐行匹配正则表达式模式

时间:2019-02-13 11:30:18

标签: python python-3.x python-2.7

我正在处理需要逐行匹配正则表达式模式的代码吗?

总有没有将所有正则表达式输出放入列表中?我有一个草稿代码,但我还没有弄清楚。尽管仍在尝试寻找解决方案。

teststr = """router#sh ip bgp        
Status codes: s suppressed, d damped, h history, * valid, > best, i - internal,
              r RIB-failure, S Stale, m multipath, b backup-path, x best-external
Origin codes: i - IGP, e - EGP, ? - incomplete

   Network          Next Hop            Metric LocPrf Weight Path
*> 6.120.0.0/18     2.2.2.11                          0 3111 2000 2485 43754 i
*> 6.120.0.0/17     2.2.2.11                          0 3111 2000 2485 43754 i
*> 13.44.61.0/24    2.2.2.11                          0 3111 4559 i
*> 13.44.62.0/24    2.2.2.11                          0 3111 4559 i"""

data = []
for line in teststr:
    if line !='':
        word = re.search('> \d............', line)
        data.append(str(word))
        print (data)

谢谢

3 个答案:

答案 0 :(得分:1)

我认为您正在尝试搜索所有网络并将其保存在列表中。

re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})/\d+',teststr)

答案 1 :(得分:1)

list.txt:

router#sh ip bgp        
Status codes: s suppressed, d damped, h history, * valid, > best, i - internal,
              r RIB-failure, S Stale, m multipath, b backup-path, x best-external
Origin codes: i - IGP, e - EGP, ? - incomplete

   Network          Next Hop            Metric LocPrf Weight Path
*> 6.120.0.0/18     2.2.2.11                          0 3111 2000 2485 43754 i
*> 6.120.0.0/17     2.2.2.11                          0 3111 2000 2485 43754 i
*> 13.44.61.0/24    2.2.2.11                          0 3111 4559 i
*> 13.44.62.0/24    2.2.2.11                          0 3111 4559 i

然后:

logFile = "list.txt"

with open(logFile) as f:
    content = f.readlines()

# you may also want to remove empty lines
content = [l.strip() for l in content if l.strip()]


# network list to save the ip's
netList = []

for line in content:
    if line.startswith("*>"):
        netList.append(line.split(" ")[1])


print(netList)

输出:

['6.120.0.0/18', '6.120.0.0/17', '13.44.61.0/24', '13.44.62.0/24']

答案 2 :(得分:0)

data = []
for line in teststr.split('\n'):
    if line !='':
        word = re.search('> \d............', line)
        data.append(str(word))
        print (data)