请教个python替换字符的问题

2012-11-20 15:03:15 +08:00
 gino
_re_imgs = re.compile('(http[s]?://?\S*\w\.(jpg|jpe|jpeg|gif|png))\w*', re.UNICODE|re.I|re.M|re.S)
_re_gist = re.compile('(http[s]?://gist.github.com/[\d]+)', re.UNICODE|re.I|re.M|re.S)
_re_con_sup = re.compile('\B!([^<>\/].+?)!\B', re.UNICODE|re.I|re.M|re.S)

#sup
if _re_con_sup.search(text):
text = _re_con_sup.sub(r'<div id="sup">\1</div>', text)
#gist
if '://gist' in text:
text = _re_gist.sub(r'<script src="\1.js"></script>',text)
#auto img
if _re_imgs.search(text):
text = _re_imgs.sub(r'<a class="imga" href="\1"><img class="lazy" border="0" style="max-width:540px;" src="./static/grey2.gif" data-original="\1"/></a>', text)

怎么对_re_con_sup过的内容就不做_re_imgs、_re_gist处理了呢,谢谢
3247 次点击
所在节点    Python
3 条回复
dreampuf
2012-11-20 19:29:55 +08:00
1. 合并到一个regex中,用"|"处理.
2. 获取所有_re_con_sup匹配的边界,在后面的捕获中一旦在这些边界中的,就视为匹配不成功。
gino
2012-11-20 23:01:20 +08:00
@dreampuf
第一个方式,我测试过了,因为regex比较多,会很麻烦
对应第二个方式,是否能在指点下,感谢了
dreampuf
2012-11-21 00:48:09 +08:00
@gino
In [1]: import re

In [2]: a = re.search(r"""(?:(?P<pic>http[s]?://?\S*\w\.(jpg|jpe|jpeg|gif|png))\w*|(?P<gist>http[s]?://gist.github.com/[\d]+)|\B!(?P<con>[^<>\/].+?)!\B)""", "http://huangx.in/a.jpg")

In [3]: a.groupdict()
Out[3]: {'con': None, 'gist': None, 'pic': 'http://huangx.in/a.jpg'}

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/52863

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX