如果您想要数字,并且您的txt文件的格式类似于前两行,即X/Y= 6,而不是{}:import re
result=[]
with open("TestData.txt") as f:
for line in f:
s = re.search(r'(?<=Y=\s)\d+',line) # pattern matches up to "Y" followed by "=" and a space "\s" then a digit or digits.
if s: # if there is a match i.e re.search does not return None, add match to the list.
result.append(s.group())
print result
['5', '6', '7']
要匹配注释中的模式,应该像这样转义句点。或者你将匹配1.2+3等字符串。。“.”有特殊的意义。在
所以re.search(r'(?<=Counting Numbers =\s)\d\.\d\.\d',s).group()
只返回1.2.3
如果它使它更显式,您可以使用s=re.search(r'(?<=X/Y=\s)\d+',line),使用完整的X/Y=\s模式。在
使用注释中的原始行和更新的行将返回:
^{2}$
这个(?<=Y=\s)被称为一个积极的lookbehind断言。在(?<=...)
如果字符串中的当前位置前面有匹配项。。。在当前位置结束