2016-12-13 34 views
1

我是一名中级Python程序员。在我的实验,我使用Linux命令输出的一些结果是这样的:使用阵列切片时的问题

OFPST_TABLE reply (xid=0x2): 
    table 0 ("classifier"): 
    active=1, lookup=41, matched=4 
    max_entries=1000000 
    matching: 
     in_port: exact match or wildcard 
     eth_src: exact match or wildcard 
     eth_dst: exact match or wildcard 
     eth_type: exact match or wildcard 
     vlan_vid: exact match or wildcard 
     vlan_pcp: exact match or wildcard 
     ip_src: exact match or wildcard 
     ip_dst: exact match or wildcard 
     nw_proto: exact match or wildcard 
     nw_tos: exact match or wildcard 
     tcp_src: exact match or wildcard 
     tcp_dst: exact match or wildcard 

我的目标是收集参数active=这是不时变量的值(在这种情况下,它仅仅是1)。我用下面的切片,但它不工作:

string = sw.cmd('ovs-ofctl dump-tables ' + sw.name) # trigger the sh command 
count = count + int(string[string.rfind("=") + 1:]) 

我想我用切片错在这里,但我尝试过很多办法,但我还是什么也没得到。有人可以帮我从这个字符串中提取active=参数的值吗?

非常感谢:)

回答

2

regex怎么样?

import re 
count += int(re.search(r'active\s*=\s*([^,])\s*,', string).group(1)) 
+0

非常感谢你..工作非常整齐.. :) –

2

1)使用正则表达式:

import re 
m = re.search('active=(\d+)', ' active=1, lookup=41, matched=4') 
print m.group(1) 

2)str.rfind返回,其中子被发现的最高指数字符串中,它会找到=(最右边的matched=4),即不是你想要的。 3)简单的切片不会对你有所帮助,因为你需要知道活动值的长度,总体来说它不是这项任务的最佳工具。

+0

谢谢澄清。 –