你可以在没有正则表达式的情况下做到这一点。
def get_sub(s, start, end):
s1 = s[s.find(start) + len(start):]
return s1[:s1.find(end)]
get_sub(s, "constString1=", ";")
>>> '31'
get_sub(s, "constString2=", ";")
>>> '16'
如果您想将其转换为另一种类型,您可以执行以下操作:
def get_sub(s, start, end, cast_to):
s1 = s[s.find(start) + len(start):]
return cast_to(s1[:s1.find(end)])
get_sub(s,"constString1=",";", int)
>>> 31
get_sub(s,"constString2=",";", float)
>>> 16.0
编辑
这种方法实际上比正则表达式更快:
t1 = timeit.Timer(stmt="""get_sub(s,"constString1=",";", int)""", setup="""s = "....00.3276021,,,constString1=31;garbage=00:00:00.0090000;constString2=16;garbage2=00.00..."
def get_sub(s, start, end, cast_to):
s1 = s[s.find(start) + len(start):]
return cast_to(s1[:s1.find(end)])""")
t2 = timeit.Timer(stmt="""int(re.search("constString1=(\d+);",s).group(1))""", setup="""import re
s = "....00.3276021,,,constString1=31;garbage=00:00:00.0090000;constString2=16;garbage2=00.00..."
""")
>>> t1.timeit()
2.829952681655172
>>> t2.timeit()
3.7208872074169506