python正则表达式如何在匹配到元素之后进行处理再将处理结果替换原文?
高洛峰
高洛峰 2016-11-10 11:15:27
0
2
523

如要处理以下markdown:

# I miss you
my name is Gina,
This is my cloum: [sdf
df](http://zhuanlan.zhihu.com/xxxzzz)
and this is my weibo:[sina blog](https://link.zhihu.com/?target=http%3A//weibo.com/u/2355944%3Fis_hot%3D1)

我写的代码:

from __future__ import unicode_literals, print_function
import re
content='''
# I miss you
my name is Gina,
This is my cloum: [sdf
df](http://zhuanlan.zhihu.com/xxxzzz)
and this is my weibo:[sina blog](https://link.zhihu.com/?target=http%3A//weibo.com/u/2355944%3Fis_hot%3D1)
'''
linklist = re.findall('\[(.+?)\]\((.+?)\)',content,re.S)
for link in linklist:
    link[0].replace("\r\n","")
    link[1].replace("\r\n","")
    link[1].replace('https://ref.zhihu.com/?redrict=','')
print (content)

显而易见的。。以上代码不能运行。。如何得到我想要的:

# I miss you
my name is Gina,
This is my cloum: [sdfdf](http://zhuanlan.zhihu.com/xxxzzz)
and this is my weibo:[sina blog](http://weibo.com/u/2355944?is_hot=1)


高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全員に返信(2)
学霸

直接replace就可以了~

python3

>>> content='''
# I miss you
my name is Gina,
This is my cloum: [sdfdf](http://zhuanlan.zhihu.com/xxxzzz)
and this is my weibo:[sina blog](https://link.zhihu.com/?target=http%3A//weibo.com/u/2355944%3Fis_hot%3D1)
'''
>>> x=content.replace(r'https://link.zhihu.com/?target=http%3A','http:')
>>> print(x)

# I miss you
my name is Gina,
This is my cloum: [sdfdf](http://zhuanlan.zhihu.com/xxxzzz)
and this is my weibo:[sina blog](http://weibo.com/u/2355944%3Fis_hot%3D1)


いいねを押す +0
三叔
from __future__ import unicode_literals, print_function
from urllib import unquote
import os, html2text, re

content='''
# I miss you
my name is Gina,
This is my cloum:[sdf
df](http://zhuanlan.zhihu.com/xxxzzz)
and this is my weibo:[sina blog](https://link.zhihu.com/?target=http%3A//weibo.com/u/2355944%3Fis_hot%3D1)
'''

def ZhiHu_LinkParser(content):
    return re.sub('(\[.+?\])(\(.+?\))', LinkReplace, content,0,re.S)

def LinkReplace(matched):
    return RRN(matched.group(1)) + unquote(RRN(matched.group(2)).replace('https://link.zhihu.com/?target=',''))

def RRN(str):
    return re.sub(r'\r*\n*',"",str)

print (ZhiHu_LinkParser(content))


いいねを押す +0
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!