码迷,mamicode.com
首页 > 编程语言 > 详细

Python 正则表达式替换特定字符为标志的字符串

时间:2014-08-20 12:33:12      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:正则表达式

Requirement:

[
{
"code": "AF",
"value": 53,
"name": "Afghanistan"
},
{
"code": "AL",
"value": 117,
"name": "Albania"
},
{
"code": "DZ",
"value": 15,
"name": "Algeria"
},
{
"code": "AD",
"value": 181,
"name": "Andorra"
},
{
"code": "AO",
"value": 15,
"name": "Angola"
}
]

将value后面的数字全部变成0 (即以value作为标志)


Regular Expressions:

import re


subject = '''
[
{
"code": "AF",
"value": 53,
"name": "Afghanistan"
},
{
"code": "AL",
"value": 117,
"name": "Albania"
},
{
"code": "DZ",
"value": 15,
"name": "Algeria"
},
{
"code": "AD",
"value": 181,
"name": "Andorra"
},
{
"code": "AO",
"value": 15,
"name": "Angola"
}
]'''


innerre = re.compile("\d+")


def replacewithin(matchobj):
    return innerre.sub("0", matchobj.group())


result = re.sub('"value": .*', replacewithin, subject)
print result



Python 正则表达式替换特定字符为标志的字符串,布布扣,bubuko.com

Python 正则表达式替换特定字符为标志的字符串

标签:正则表达式

原文地址:http://blog.csdn.net/guaguastd/article/details/38703741

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!