Python 正则提取并赋值的问题

hide1713 2008-01-13 12:09:14
我查过论坛的历史,发现没这样的问题。
我想提取下面一个个字符串的内容
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个数据.分别赋值到两个变量.如何做是最简洁的方法?
请指教,谢谢
...全文
619 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
freekongjian 2010-12-02
  • 打赏
  • 举报
回复
地对地导弹v
hide1713 2008-02-23
  • 打赏
  • 举报
回复
如何结贴?我给分以后每次都显示密码验证Error Password 1 我已经登陆了啊.哪里来的密码验证
Hounvie 2008-02-23
  • 打赏
  • 举报
回复
iambic 好样的!
iambic 2008-02-23
  • 打赏
  • 举报
回复
结贴的时候需要密码的。
thewintersun 2008-02-18
  • 打赏
  • 举报
回复
做个记号
den88 2008-01-29
  • 打赏
  • 举报
回复
支持1 楼
hide1713 2008-01-13
  • 打赏
  • 举报
回复
谢谢.讲得很清楚.
iambic 2008-01-13
  • 打赏
  • 举报
回复
#!/usr/bin/python


s = '''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'''


import re

m = re.search(r'^lo:\s*(\d+)\s+(?:\d+\s+){7}(\d+)', s, re.M)
print m.groups()


ss = re.search(r'^lo:.*', s, re.M).group()
all = re.findall(r'\d+', ss)
print all[0], all[8]

ss = re.search(r'(?<=^lo:).*', s, re.M).group()
all = re.split(r'\s+', ss)
print all[0], all[8]

37,720

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧