从String Python中提取子串

时间:2014-11-08 23:00:57

标签: python regex substring function

我正在尝试从字符串

中提取以下子字符串
-- CVS Header: $Source: /CVS/oracle11i/database/erp/apps/pkgspec/wwt_prime_pkg.p
ls,v $, $Revision: 1.14 $, $Author: $, $Date: 2014/09/23 21:41:15 $

我要提取的字符串:$Revision: 1.14 (or just 1.14)

我的代码如下:

from sys import *
from os.path import *
import re 

script, filename = argv

print "Filename: %s\n" % filename

def check_string():
    found = False
    with open(filename) as f:
        for line in f:
        if re.search("(?<=\$Revision: ) 1.14", line):
            print line
            found = True
        if not found:
            print "No Header exists in %s" % filename

check_string()

这似乎不起作用。

有什么建议吗?

谢谢!

5 个答案:

答案 0 :(得分:2)

if re.search("(?<=\$Revision: ) 1.14", line):

由于您尝试匹配:1.14之间的两个空格,您的广告系列无法正常工作,请尝试:

if re.search("(?<=\$Revision: )1.14", line):

if re.search("\$Revision:\s+1.14", line):

答案 1 :(得分:1)

你的正则表达式在冒号和版本号之间需要两个空格,输入只包含一个空格。

答案 2 :(得分:1)

如果我理解你并且分裂应该做你想做的事:

if "$Revision:" in line:
    print(line.split("$Revision: ")[1].split()[0])
1.14


In [6]: line ="""
   ...: -- CVS Header: $Source: /CVS/oracle11i/database/erp/apps/pkgspec/wwt_prime_pkg.p
   ...: ls,v $, $Revision: 1.14 $, $Author: $, $Date: 2014/09/23 21:41:15 $
   ...: """

In [7]: line.split("$Revision: ")  # split the line at $Revision: 
Out[7]: 
['\n-- CVS Header: $Source: /CVS/oracle11i/database/erp/apps/pkgspec/wwt_prime_pkg.p\nls,v $, ',
 '1.14 $, $Author: $, $Date: 2014/09/23 21:41:15 $\n']

# we use indexing to get the first element after $Revision:  in the string
In [8]: line.split("$Revision: ")[1] 
# which becomes the substring below
Out[8]: '1.14 $, $Author: $, $Date: 2014/09/23 21:41:15 $\n'

# if we call split again we split that substring on whitespace into individual strings
In [10]: '1.14 $, $Author: $, $Date: 2014/09/23 21:41:15 $\n'.split()
Out[10]: ['1.14', '$,', '$Author:', '$,', '$Date:', '2014/09/23', '21:41:15', '$']

# using indexing again we extract the first element which is the  revision number
In [11]: '1.14 $, $Author: $, $Date: 2014/09/23 21:41:15 $\n'.split()[0]
Out[11]: '1.14'

$Date

是一样的
 date  = line.split("$Date: ")[1].split()[0]

如果您只想检查字符串中的子字符串,请使用in

if "$Revision: 1.14" in line:
    print line

答案 3 :(得分:0)

>>> import re
>>> string="""-- CVS Header: $Source: /CVS/oracle11i/database/erp/apps/pkgspec/wwt_prime_pkg.p
... ls,v $, $Revision: 1.14 $, $Author: $, $Date: 2014/09/23 21:41:15 $"""
>>> re.findall(r'\$Revision:\s*([0-9.]*)',string,re.DOTALL) # if more than one such value is to be searched
['1.14']   
>>> re.search(r'\$Revision:\s*([0-9.]*)',string,re.DOTALL).group(1) # if only one such value neeeds to be found 
'1.14'

答案 4 :(得分:0)

import sys

def check_string(f,target):
    for line in f:
        if line.find(target)>=0:
            return line

script, filename = argv

f = open(filename)
rev_line = check_string(f,'Revision: 1.14')
if rev_line:
    ...
else:
    ...

check_string函数

  1. 无需regexp
  2. line.find(target)在失败时返回-1,成功时target中的line索引
  3. 如果索引不小于0我们匹配,那么我们返回line
  4. 如果我们找不到匹配项,我们会退出该函数的边框,返回None
  5. 调用程序

    在通常的样板文件之后,我们将变量rev_line分配给check_string返回的内容。如果我们未找到'Revision: 1.14',则rev_lineNone,否则为包含目标的整行。继续做两种情况下要做的事情。

    修改

    如果在编写程序时未知修订号,则有两种情况

    1. 修订号来自文件或以其他方式计算,在执行时知道

      target = 'Revision: %d.%d' % (major, minor)
      rev_line = check_string(f, target)
      
    2. 在检查时未完全知道修订号,在这种情况下,您构建包含正则表达式的target字符串并修改{{1}的内部结构},代替你写的check_string if line.find(target)>=0:,它与你在第一个地方写的非常相似,但正则表达式不再硬编码到函数中,你就可以了。可以自由地在主程序体中确定它。

    3. 总而言之,if re.search(target, line):更好,因为你总能建立一个&#34;常数&#34;正则表达式...