如何在python中正则化特定键的值

2024-06-12 03:21:52 发布

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

我有一个长字符串,键值的格式如下:

"info":"infotext","day":"today","12":"here","info":"infotext2","info":"infotext3"

我想得到所有“信息”键的值(=infotexts)。如何做到这一点?在


Tags: 字符串info信息todayhere格式键值day
3条回答

使用此正则表达式(?<="info":")(.+?)(?=")

只要您的infotext不包含(转义)引号,您可以尝试如下操作:

>>> m = re.findall(r'"info":"([^"]+)', str)
>>> m
['infotext', 'infotext2', 'infotext3']

我们只需匹配"info":"和尽可能多的非"字符(这些字符被捕获并返回)。在

使用json,Luke

s = '"info":"infotext","day":"today","12":"here","info":"infotext2","info":"infotext3"'

import json

def pairs_hook(pairs):
    return [val for key, val in pairs if key == 'info']

p = json.loads('{' + s + '}', object_pairs_hook=pairs_hook)
print p # [u'infotext', u'infotext2', u'infotext3']

来自the docs

object_pairs_hook is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict.

为了完整起见,下面是一个正则表达式,它执行相同的操作:

^{pr2}$

它还处理:左右的空格和字符串中的转义引号,例如

 "info"  :   "some \"interesting\" information"

相关问题 更多 >