如何在多行中搜索特定行并将值存储在变量中
How to search for a specific line in multi line and store value in a variable
我已将命令 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.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)
我已将命令 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.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)