Python 正则提取并赋值的问题
我查过论坛的历史,发现没这样的问题。
我想提取下面一个个字符串的内容
Inter-| Receive | Transmit
face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed
lo:118270468 468636 0 0 0 0 0 0 118270468 468636 0 0 0 0 0 0
ipoib0:14915584 162128 0 0 0 0 0 0 0 0 4 4 0 0 0 0
eth0:/10 0 0 0 0 0
eth1: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
第一个问题:
我要提取
lo:118270468 468636 0 0 0 0 0 0 118270468 468636 0 0 0 0 0 0
这一行的第1和第9个数据
当我使用这样分组匹配时
(?<=lo:)((\d*)\s+)+
这一行正确匹配.但是match.group 没有正确的把数据分组
后来我换成这样.匹配前9个数据.group返回就正常了.
(?<=lo:)(\d*)\s+(\d*)\s+(\d*)\s+(\d*)\s+(\d*)\s+(\d*)\s+(\d*)\s+(\d*)\s+(\d*)\s+(\d*)\s+
我的问题是:python能否处理嵌套的()定义? 如果我有上百个数据.难道正则表达式要重复上百遍?虽然可以用split(),但我想知道正则是如何处理这样的情况的.
另外一个问题.
rawstr是模式,matchstr是源字符
rawstr = r"(?<=lo:)(\d*)\s+(\d*)\s+(\d*)\s+(\d*)\s+(\d*)\s+(\d*)\s+(\d*)\s+(\d*)\s+(\d*)\s+(\d*)\s+"
matchstr = """Inter-| Receive | Transmit
face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed
lo:118270468 468636 0 0 0 0 0 0 118270468 468636 0 0 0 0 0 0
ipoib0:14915584 162128 0 0 0 0 0 0 0 0 4 4 0 0 0 0
eth0:2613318398 2981750012 0 0 0 0 0 92252718 858598796 2901387349 0 0 0 0 0 0
eth1: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
"""
in=re.sub(rawstr,r'/1',matchstr)
out=re.sub(rawstr,r'/9',matchstr)
这时却匹配不成功,st是整个源字符串. 我想使用正则表达式/1 /9 这样的方法.取出lo行第1和第9个数据.分别赋值到两个变量.如何做是最简洁的方法?
请指教,谢谢