【问题标题】:How to search for a specific line in multi line and store value in a variable如何在多行中搜索特定行并将值存储在变量中
【发布时间】:2019-04-23 06:52:22
【问题描述】:

我已将命令 chage -l user 的输出存储在变量 output 中,需要检查用户帐户密码是否未过期或将在 90 天内过期。

import re

output = '''Last password change                                    : Aug 26, 2017
Password expires                                        : never
Password inactive                                       : never
Account expires                                         : never
Minimum number of days between password change          : 0
Maximum number of days between password change          : 99999
Number of days of warning before password expires       : 7
'''

regexp = re.compile(r'Password expires [ ]*(:*?)')
match = regexp.match(output)
if match:
    VALUE = match.group(2)

现在,我需要将值存储在一个变量中以继续前进,但无法做到这一点。以上是我的代码。理想情况下,VALUE 应该是“从不”。

【问题讨论】:

  • re.findall('Password expires\s+: (\w+)', output)[0] 怎么样?

标签: python regex python-re


【解决方案1】:

re.match 不会在整个字符串中查找模式,而是会在字符串的开头匹配它(就像正则表达式以^ 开头一样)。所以你需要re.search,它将检查整个目标字符串的模式:

import re
output = '''Last password change                                    : Aug 26, 2017
Password expires                                        : never
Password inactive                                       : never
Account expires                                         : never
Minimum number of days between password change          : 0
Maximum number of days between password change          : 99999
Number of days of warning before password expires       : 7
'''

regexp = re.compile(r'Password expires\s+: (.*)')
match = regexp.search(output)
if match:
    VALUE = match.group(1)
    print(VALUE)

【讨论】:

    猜你喜欢
    • 2022-10-17
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多