推荐学习书目
› 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 · Nov 20, 2012 · 4398 views
    This topic created in 5056 days ago, the information mentioned may be changed or developed.
    _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处理了呢,谢谢
    Supplement 1  ·  Nov 22, 2012
    已经搞定了,谢谢了
    3 replies  •  1970-01-01 08:00:00 +08:00
    dreampuf
        1
    dreampuf  
       Nov 20, 2012   ❤️ 1
    1. 合并到一个regex中,用"|"处理.
    2. 获取所有_re_con_sup匹配的边界,在后面的捕获中一旦在这些边界中的,就视为匹配不成功。
    gino
        2
    gino  
    OP
       Nov 20, 2012
    @dreampuf
    第一个方式,我测试过了,因为regex比较多,会很麻烦
    对应第二个方式,是否能在指点下,感谢了
    dreampuf
        3
    dreampuf  
       Nov 21, 2012
    @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'}
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   983 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 18:30 · PVG 02:30 · LAX 11:30 · JFK 14:30
    ♥ Do have faith in what you're doing.