V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
gino
V2EX  ›  Python

请教个python替换字符的问题

  •  
  •   gino · 2012-11-20 15:03:15 +08:00 · 3234 次点击
    这是一个创建于 4189 天前的主题,其中的信息可能已经有所发展或是发生改变。
    _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处理了呢,谢谢
    第 1 条附言  ·  2012-11-22 13:44:22 +08:00
    已经搞定了,谢谢了
    3 条回复    1970-01-01 08:00:00 +08:00
    dreampuf
        1
    dreampuf  
       2012-11-20 19:29:55 +08:00   ❤️ 1
    1. 合并到一个regex中,用"|"处理.
    2. 获取所有_re_con_sup匹配的边界,在后面的捕获中一旦在这些边界中的,就视为匹配不成功。
    gino
        2
    gino  
    OP
       2012-11-20 23:01:20 +08:00
    @dreampuf
    第一个方式,我测试过了,因为regex比较多,会很麻烦
    对应第二个方式,是否能在指点下,感谢了
    dreampuf
        3
    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'}
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1317 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 17:55 · PVG 01:55 · LAX 10:55 · JFK 13:55
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.