简体   繁体   English

python 中正常运行时间命令的正则表达式

[英]regex for uptime command in python

"uptime" command has many different outputs. “正常运行时间”命令有许多不同的输出。 I'm trying to build regex pattern to match days and minutes.我正在尝试构建正则表达式模式以匹配日期和分钟。 Need some help on this.在这方面需要一些帮助。 Different outputs of uptime:正常运行时间的不同输出:

            15:22:04 up 45 days,  2:34,  2 users,  load average: 0.94, 1.17, 1.37
            15:30:12 up 21 min,  2 users,  load average: 1.56, 1.18, 1.18
            15:30:39 up 15:30,  1 user,  load average: 0.27, 0.40, 0.48

I tried the following but it works only for one of the output:我尝试了以下方法,但它仅适用于 output 之一:

import re;
uptime_parser = re.compile('up\s+(\d+\s+\w+,\s+\d+:\d+)')

Expected output for each case:每个案例的预期 output:

  1. up 45 days, 2:34向上 45 天,2:34
  2. up 21 min上升 21 分钟
  3. up 15:30 15:30 起

To match the different variations:为了匹配不同的变化:

\bup\s+(?:(?:\d+\s+days,)?\s*\d{1,2}:\d{1,2}|\d+\s+min)\b

Explanation解释

  • \bup\s+ Match the word up and 1+ whitespace chars \bup\s+匹配单词up和 1+ 个空白字符
  • (?: Non capture group for the alternatives (?:备选方案的非捕获组
    • (?:\d+\s+days,)? Optionally match 1+ digits, 1+ whitespace chars and days,可选择匹配 1 个以上的数字、1 个以上的空白字符和days,
    • \s*\d{1,2}:\d{1,2} Match optional whitespace chars and 1-2 digits : 1-2 digits \s*\d{1,2}:\d{1,2}匹配可选的空白字符和 1-2 位数字: 1-2 位数字
    • | Or要么
    • \d+\s+min Match 1+ digits, 1+ whitespace chars and min \d+\s+min匹配 1+ 个数字,1+ 个空白字符和min
  • ) Close the non capture group )关闭非捕获组
  • \b A word boundary to prevent a partial word match \b防止部分单词匹配的单词边界

See a regex demo .请参阅正则表达式演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM