大家好,我正在使用re.match函数从文件中提取一行中的字符串。
我的代码如下:
## fp_tmp => pointer of file
for x in fp_tmp:
try:
cpuOverall=re.match(r"(Overall CPU load average)\s+(\S+)(%)",x)
cpuUsed=re.match(r"(Total)\s+(\d+)(%)",x)
ramUsed=re.match(r"(RAM Utilization)\s+(\d+\%)",x)
####Not Work####
if cpuUsed is not None: cpuused_new=cpuUsed.group(2)
if ramUsed is not None: ramused_new=ramUsed.group(2)
if cpuOverall is not None: cpuoverall_new=cpuOverall.group(2)
except:
searchbox_result = None
每个字段都从下面的相应行中提取:
ramUsed => RAM Utilization %2
cpuUsed => Total %4
cpuOverall => Overall CPU load average 12%
当我执行脚本时,所有变量都返回一个值:无。使用其他变量,脚本可以正确运行。
为什么在这种情况下代码不起作用?我使用python3
我认为问题是没有读到的字符%。
您有什么建议吗?
cpuOverall
行:您忘了该行开头有更多信息。更改为
'.*(Overall CPU load average)\s+(\S+)(%)'
cpuUsed
行:您忘了该行开头有更多信息。另外,由于添加了(%)
,因此组计数为关闭。更改为
'.*(Total)\s+%(\d+)'
ramUsed
行:您忘了该行的开头还有更多信息。此外,您的%
也已转义-不在其他两个表达式中,因此没有必要。更改为
'.*(RAM Utilization)\s+%(\d+)'
记住re.match
寻找完全匹配从头开始:
如果
re.match
的零个或多个字符在开头与正则表达式模式匹配,则返回相应的匹配对象。 [..]