python regex多重查找

2024-05-16 16:00:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从web请求中正确提取一些Cookie。 基本上我有这个字符串:

 str="""Cole_gal_langid=0; Expires=Sun, 14-Jul-13 20:37:22 GMT, Cole_gal_styleid=4; Expires=Sun, 14-Jul-13 20:37:22 GMT, Cole_gal_viewid=test; Expires=Sun, 14-Jul-13 20:37:22 GMT, Cole_gal_appid=gal; Expires=Sun, 14-Jul-13 20:37:22 GMT, Cole_gal_navk=common.invalidBookmark; Expires=Sun, 14-Jul-13 20:37:22 GMT, Cole_gal_trans=InvalidBookmark; Expires=Sun, 14-Jul-13 20:37:22 GMT"""

我要删除此字符串中的所有“Expires=Sun,14-Jul-13 20:37:22 GMT”条目。 所以这个字符串变成了:

str="""Cole_gal_langid=0; Cole_gal_styleid=4; Cole_gal_viewid=test; Cole_gal_appid=gal; Cole_gal_navk=common.invalidBookmark; Cole_gal_trans=InvalidBookmark;"""

我想用Re来做这个:

import re

str="""Cole_gal_langid=0; Expires=Sun, 14-Jul-13 20:37:22 GMT, Cole_gal_styleid=4; Expires=Sun, 14-Jul-13 20:37:22 GMT, Cole_gal_viewid=test; Expires=Sun, 14-Jul-13 20:37:22 GMT, Cole_gal_appid=gal; Expires=Sun, 14-Jul-13 20:37:22 GMT, Cole_gal_navk=common.invalidBookmark; Expires=Sun, 14-Jul-13 20:37:22 GMT, Cole_gal_trans=InvalidBookmark; Expires=Sun, 14-Jul-13 20:37:22 GMT"""

a = re.search('(Cole_gal_*.\=*)[^;]*', str)
if a:
   quote = "Regex found this: "+a.group(0)+"\r\n"
   print quote

不幸的是,我只得到一个结果,而不是所有的实际饼干

任何帮助或建议都将不胜感激。你知道吗

谢谢!你知道吗


Tags: 字符串testcommonappidjulsungalexpires
3条回答

看看re.finditer函数。你知道吗

^{}呢?你知道吗

Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match.

删除re.sub作业中出现的多个模式:

>>> re.sub(r'Expires=.*?GMT([,;]|$)', '', s)
'Cole_gal_langid=0;  Cole_gal_styleid=4;  Cole_gal_viewid=test;  Cole_gal_appid=gal;  Cole_gal_navk=common.invalidBookmark;  Cole_gal_trans=InvalidBookmark; '

相关问题 更多 >