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
Livid
V2EX  ›  Python

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

  •  
  •   Livid · 2012-06-05 13:33:56 +08:00 · 3554 次点击
    这是一个创建于 4315 天前的主题,其中的信息可能已经有所发展或是发生改变。
    下面这个是目前 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 条回复    1970-01-01 08:00:00 +08:00
    phuslu
        1
    phuslu  
       2012-06-05 13:44:32 +08:00
    试下
    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  
       2012-06-05 13:51:09 +08:00
    写了个test, https://gist.github.com/2872926

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

    我认为应该在转义前,检查是否存在该用户。感觉用markdown的block来处理这个问题是个不错的选择。
    Livid
        3
    Livid  
    MOD
    OP
       2012-06-15 23:43:32 +08:00
    @phuslu 非常感谢。已经部署。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5224 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 07:22 · PVG 15:22 · LAX 00:22 · JFK 03:22
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.