gpt4 book ai didi

python - 从 Python 字符串中提取子字符串

转载 作者:太空宇宙 更新时间:2023-11-03 15:10:58 25 4
gpt4 key购买 nike

我正在尝试从字符串中提取以下子字符串

-- 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()

这似乎不起作用。

有什么建议吗?

谢谢!

最佳答案

如果我对你的理解正确,那么 split 应该做你想做的:

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

关于python - 从 Python 字符串中提取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26823034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com