Python:将一个特殊的角色与正则表达式匹配

问题描述 投票:0回答:1

大家好,我正在使用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

我认为问题是没有读到的字符%。

您有什么建议吗?

regex python-3.x matching
1个回答
0
投票

cpuOverall行:您忘了该行开头有更多信息。更改为

'.*(Overall CPU load average)\s+(\S+)(%)'

cpuUsed行:您忘了该行开头有更多信息。另外,由于添加了(%),因此组计数为关闭。更改为

'.*(Total)\s+%(\d+)'

ramUsed行:您忘了该行的开头还有更多信息。此外,您的%也已转义-不在其他两个表达式中,因此没有必要。更改为

'.*(RAM Utilization)\s+%(\d+)'

记住re.match寻找完全匹配从头开始

如果re.match的零个或多个字符在开头与正则表达式模式匹配,则返回相应的匹配对象。 [..]

© www.soinside.com 2019 - 2024. All rights reserved.