推荐学习书目
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
Livid
279.45D
571.17D
V2EX  ›  Python

向大家请教关于 Python 用正则表达式匹配 mention 的问题

  •  
  •   Livid ·
    PRO
    · Jun 5, 2012 · 4305 views
    This topic created in 5098 days ago, the information mentioned may be changed or developed.
    下面这个是目前 PB3 的 mentions 转换的函数:

    def mentions(value):
    return re.sub(r'(\A|\s)@(\w+)', r'\1@<a href="/member/\2">\2</a>', value)

    有个问题就是,如果在 @ 的前面有中文,比如@Livid,既如字后面没有空格的时候,就不会触发转换。

    但是实际上 notification 的触发是没有问题的,因为 notification 里用的是另外一段转换规则。

    关于在正文中的这段 mentions 的转换函数,大家有什么好办法实现可以让 @ 跟在中文后面么?
    3 replies    1970-01-01 08:00:00 +08:00
    phuslu
        1
    phuslu  
       Jun 5, 2012
    试下
    return re.sub(ur'(\A|\s|[\u4e00-\u9fa5])@(\w+)', ur'\1@<a href="/member/\2">\2</a>', value)
    需要 value 是unicode,或者 sys.setdefaultencoding('utf-8')
    c
        2
    c  
       Jun 5, 2012
    写了个test, https://gist.github.com/2872926

    如果要求@前面有字母也要求能转换,如何避免别人输入的邮箱地址,比如 value = "[email protected] xxx"

    我认为应该在转义前,检查是否存在该用户。感觉用markdown的block来处理这个问题是个不错的选择。
    Livid
        3
    Livid  
    MOD
    OP
    PRO
       Jun 15, 2012
    @phuslu 非常感谢。已经部署。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5385 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 96ms · UTC 01:28 · PVG 09:28 · LAX 18:28 · JFK 21:28
    ♥ Do have faith in what you're doing.