2017-06-19 70 views
1

我有一个包含以下日志的文件。现在我想知道我的TD_Map字符串在哪里。我可以通过str.find()方法实现。但有没有办法将完整的字符串作为返回值?就像这个例子一样,我必须得到TD_Map2。 我必须搜索TD_Map字符串,因为其余部分可以是任何整数常量。如何在通过python搜索文件中的部分字符串时获取完整的字符串值?

Running 
OK, start the cluster assignment. 
: 6035 
Warning: The Default Cluster size results in a cluster with multiple Amps on the same Clique. 
The cluster assignment is complete. 
Reading 
da 6-7 
Running  
OK. 
The AMPs 6 to 7 are deleted.> 
Reading 
ec 
Running 
OK. 
The session terminated. TD_Map2 is saved.> 

回答

1

有很多方法可以做到这一点,但它似乎是一个不错的用例的正则表达式:

import re 

s = """Running 
OK, start the cluster assignment. 
: 6035 
Warning: The Default Cluster size results in a cluster with multiple Amps on the same Clique. 
The cluster assignment is complete. 
Reading 
da 6-7 
Running  
OK. 
The AMPs 6 to 7 are deleted.> 
Reading 
ec 
Running 
OK. 
The session terminated. TD_Map22 is saved.> 
""" 

match = re.search('TD_Map([\d]+)', s) 
print(match.group(0)) # Print whole "TD_Map2" 
print(match.group(1)) # Print only the number "2" 

输出:

TD_Map2 
2 
+0

感谢help.It工作。 –

+0

@BiswajitMaharana我增加了一种方法来获得'TD_Map'后面的数字,如果你喜欢那样的话。 –

+0

是的,这两个答案对我有用。万分感谢。 –