Skip to main content
 首页 » 编程设计

python之如何在 python 中对特定键的值进行正则表达式

2025年05月04日23xiaohuochai

我有一个长字符串,其中包含以下格式的键值:

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

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

请您参考如下方法:

使用 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.

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

rg = r'''(?x) 
 
    "info" 
    \s* : \s* 
    " 
        ( 
            (?:\\.|[^"])* 
        ) 
    " 
''' 
re.findall(rg, s) # ['infotext', 'infotext2', 'infotext3'] 

这也处理 : 周围的空格和字符串内的转义引号,例如

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