我有一个从API调用返回的子字符串:
in_string="JID=1234; path=/demand; HttpOnly; Secure, OPU=; expires=Thu, 01-Jan-1970 01:00:00 GMT; path=/Demand; secure, OA_OS=$66+Y=; expires=Tue, 04-Mar-1990 15:55:22 GMT; path=/; secure"
我需要一种可靠的方法来始终提取“1234”我的当前解决方案似乎不优雅,如果字符串改变顺序,它将不会处理:
in_string.split(';')[0].replace('JID=','')
有没有更好的办法?
谢谢,
你考虑过使用正则表达式吗?
import re
in_string="JID=1234; path=/demand; HttpOnly; Secure, OPU=; expires=Thu, 01-Jan-1970 01:00:00 GMT; path=/Demand; secure, OA_OS=$66+Y=; expires=Tue, 04-Mar-1990 15:55:22 GMT; path=/; secure"
JID_number_pattern = re.compile(r'JID=\d{1,}')
JID_number = re.search(JID_number_pattern,in_string)
if JID_number:
print (JID_number.group(0).replace('JID=',''))
# output
1234