gpt4 book ai didi

Python 正则表达式 行内的任一/或

转载 作者:太空宇宙 更新时间:2023-11-03 17:49:47 26 4
gpt4 key购买 nike

我已经进行了大量搜索,但无法找到正则表达式一行并将值拆分为两个变量组件的解决方案。我正在使用 python2.6 并试图弄清楚如何将整数正则表达式为值变量并将文本正则表达式为度量变量。输出信息是从运行 netstat -s 的子进程命令中提取的。
下面的匹配将仅提供前 6 行,但不提供字符串在前的底部行。我尝试在括号内使用 or 条件,但这不起作用,尝试 (?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

最佳答案

我会忘记在这里使用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))

关于Python 正则表达式 行内的任一/或,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29262768/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com