我做了很多次搜索但是找不到正则表达式的解决方案并将值拆分为两个变量组件。我正在使用python2.6并试图弄清楚如何将整数正则表达为值变量并将文本复制到度量变量中。输出信息从运行netstat -s的子进程命令中提取
以下匹配仅提供前6行,但不提供字符串优先的底部行。我尝试在括号内使用或条件不起作用,尝试(?P<value>[0-9]+|\w+\s[0-9]+)
我一直在使用这个网站,这真的很有帮助,但仍然没有运气,https://regex101.com/r/yV5hA4/3#python
任何有关使用其他方法的帮助或想法都将受到赞赏 的代码:
for line in output.split("\n"):
match = re.search(r"(?P<value>[0-9]+)\s(?P<metric>\w+.*)", line, re.I)
if match:
value, metric = match.group('value', 'metric')
print "%s => " % value + metric
试图成为正则表达式的是什么:
17277 DSACKs received
4 DSACKs for out of order packets received
2 connections reset due to unexpected SYN
10294 connections reset due to unexpected data
48589 connections reset due to early user close
294 connections aborted due to timeout
TCPDSACKIgnoredOld: 15371
TCPDSACKIgnoredNoUndo: 1554
TCPSpuriousRTOs: 2
TCPSackShifted: 6330903
TCPSackMerged: 1883219
TCPSackShiftFallback: 792316
答案 0 :(得分:1)
我会忘记在这里使用re
,并且只做这样的事情:
for line in output.split("\n"):
value = None
metric = ""
for word in line.split():
if word.isdigit():
value = int(word)
else:
metric = "{} {}".format(metric, word)
print "{} => {}".format(metric.strip(":"), value)
有一点需要注意的是,任何包含两个或更多数字的行只能报告最后一行,但这并不比现有方法处理这种情况更糟糕......
编辑:错过了OP在Python 2.6上,在这种情况下,这应该可行:
for line in output.split("\n"):
value = None
metric = ""
for word in line.split():
if word.isdigit():
value = int(word)
else:
metric = metric + " " + word
print "%s => %s" % (metric.strip(":"), str(value))