Python关于正则表达式

时间:2017-04-05 09:12:58

标签: python regex

我对使用正则表达式re有疑问 如果我只想在以下内容中打印处理器时间值0.394519574284646

Readings       : \\demoweb01\processor(_total)\% processor time :

                 0.394519574284646





PSComputerName : DEMOWEB01

RunspaceId     : 8c9e3d4b-8908-4a30-bef4-1f26d4a511bb

Timestamp      : 4/3/2017 2:39:30 PM

CounterSamples : {Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSa

                 mple}



Readings       : \\demoweb01\processor(_total)\% processor time :

                 1.69883362197086

它应该尝试在processor time :之后找到单词吗?另外,如何处理空间线?

1 个答案:

答案 0 :(得分:1)

这是正在处理空间和正面的正则表达式。新线路 -

r'processor\s+time\s*:\s*(\d+(?:\.\d+)?)'

示例运行 -

>>> output = """Readings       : \\demoweb01\processor(_total)\% processor time :
... 
...                  0.394519574284646
... 
... 
... 
... 
... 
... PSComputerName : DEMOWEB01
... 
... RunspaceId     : 8c9e3d4b-8908-4a30-bef4-1f26d4a511bb
... 
... Timestamp      : 4/3/2017 2:39:30 PM
... 
... CounterSamples : {Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSa
... 
...                  mple}
... 
... 
... 
... Readings       : \\demoweb01\processor(_total)\% processor time :
... 
...                  1.69883362197086"""
>>> import re
>>> re.findall(r'processor\s+time\s*:\s*(\d+(?:\.\d+)?)', output)
['0.394519574284646', '1.69883362197086']