我有一个像这样的python字符串:
"""
{id: 'id_0_4', value: '8450223051', name: 'XAD3', parent: 'id_0'},
{id: 'id_0_5', value: '509071269', name: 'ABSD', parent: 'id_0'}
"""
从字符串中,我想删除value
之后显示的数字周围的单引号。
如何编写只检测此类数字并替换它们周围引号的正则表达式?
答案 0 :(得分:5)
捕获组中的数字,重新插入组:
>>> import re
>>> s = """{id: 'id_0_4', value: '8450223051', name: 'XAD3', parent: 'id_0'}, {id: 'id_0_5', value: '509071269', name: 'ABSD', parent: 'id_0'}"""
>>> re.sub("'(\d+)'", r'\1', s)
"{id: 'id_0_4', value: 8450223051, name: 'XAD3', parent: 'id_0'}, {id: 'id_0_5', value: 509071269, name: 'ABSD', parent: 'id_0'}"
或者,如果这必须特定于'value'之后的数字:
>>> re.sub("(value:\s*)'(\d+)'", r'\1\2', s)
"{id: 'id_0_4', value: 8450223051, name: 'XAD3', parent: 'id_0'}, {id: 'id_0_5', value: 509071269, name: 'ABSD', parent: 'id_0'}"