在Python中查找字符串中的模式

时间:2013-10-28 06:17:12

标签: python regex

我是Python的新手。

我有一个字符串打印表(及其内容),就像下面的

一样
Name         At time Last  Inter\ Max    Logfile Location               Status  
                     time   val   log                                           
                           (mins) files                                         
------------ ------- ----- ------ ------ ------------------------------ ------- 
foo1           now   16:00   60   100    flash:/schedule/foo1/          Job     
                                                                        under   
                                                                        progress
foo2           now     -     60   100    -                              Waiting 
tech-support   now   16:00   60   100    flash:/schedule/tech-support/  Job     
                                                                        under   
                                                                        progress

我需要找到表中存在字符串“Job under progress”的次数。我尝试了len( re.findall( pattern, string ) )len( re.findall("(?=%s)" % pattern, string) ),但似乎都没有。

有更好的建议吗?

1 个答案:

答案 0 :(得分:3)

data = """
Name         At time Last  Inter\ Max    Logfile Location               Status  
                     time   val   log                                           
                           (mins) files                                         
------------ ------- ----- ------ ------ ------------------------------ ------- 
foo1           now   16:00   60   100    flash:/schedule/foo1/          Job     
                                                                        under   
                                                                        progress
foo2           now     -     60   100    -                              Waiting 
tech-support   now   16:00   60   100    flash:/schedule/tech-support/  Job     
                                                                        under   
                                                                        progress
                                                                        """
import re
print len(re.findall("Job\s+under\s+progress", data))

<强>输出

2

修改 如果它在同一行,你根本不需要regEx

data = """
Name         At time Last  Inter\ Max    Logfile Location               Status  
                     time   val   log                                           
                           (mins) files                                         
------------ ------- ----- ------ ------ ------------------------------ ------- 
foo1           now   16:00   60   100    flash:/schedule/foo1/          Job under progress
foo2           now     -     60   100    -                              Waiting 
tech-support   now   16:00   60   100    flash:/schedule/tech-support/  Job under progress
"""

print sum(1 for line in data.split("\n") if "Job under progress" in line)

<强>输出

2