Skip to main content
 首页 » 编程设计

python之Python 中的正则表达式之奇怪的行为

2024年08月29日37rubylouvre

我想解析 uptime Unix 命令的输出。 这是两个不同的样本:

14:25  up 1 day,  1:24, 2 users, load averages: 0,56 0,48 0,47 
14:25  up 1:24, 2 users, load averages: 0,56 0,48 0,47 

(我使用的语言是Python)

所以,假设上面的两个样本被保存到变量s1和s2中。

这是我写的代码:

>>> RE = r''' 
    ((\d) \s day)?        # this should match "n day" if it's there  
    .*?                   # this should match everything until the next regex 
    \s(\d{1,2}):(\d{1,2}) # this should match a space followed by "hh:mm" 
''' 
 
>>> print re.match(RE, s1, re.VERBOSE).groups() 
(None, None, '1', '24') 
>>> print re.match(RE, s2, re.VERBOSE).groups() 
(None, None, '1', '24') 

正则表达式的第二部分,即获取正常运行时间的小时-分钟的部分,运行完美。但为什么元组的第一部分总是 None?我错过了什么?这是贪婪还是非贪婪问题?

请您参考如下方法:

您想将 .*? 移到可选的日组中并使用 .search():

RE = r''' 
    (?:(\d) \s day.*?)?   # this should match "n day" if it's there 
    \s(\d{1,2}):(\d{1,2}) # this should match a space followed by "hh:mm" 
''' 

演示:

>>> RE = r''' 
...     (?:(\d) \s day.*?)?        # this should match "n day" if it's there 
...     \s(\d{1,2}):(\d{1,2}) # this should match a space followed by "hh:mm" 
... ''' 
>>> print re.search(RE, s1, re.VERBOSE).groups() 
('1', '1', '24') 
>>> print re.search(RE, s2, re.VERBOSE).groups() 
(None, '1', '24') 

模式锚定在 : 上,然后回溯。 .*? 然后匹配拍号前的整个文本,满足模式。

通过移动 .*? 部分 到 可选的 day 组(在我的版本中不捕获)你保证它赢了不要回溯过去的 day 文字文本。