推荐学习书目
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
zmrenwu
V2EX  ›  Python

Python re.sub() 的一个奇怪问题?

  •  
  •   zmrenwu · Nov 27, 2016 · 2675 views
    This topic created in 3461 days ago, the information mentioned may be changed or developed.
    >>> def mark(mo):
                print(mo.group(1))
                return mo.group(1)
    
    >>> re.sub(r'@(yangxg)|@(zengshao)|@(zmrenwu)', mark, '@yangxg @zengshao @zmrenwu')
    yangxg
    None
    None
    

    原本的的意图去掉每个用户名前的 @ 符号,期望的输入应该是:yangxg zengshao zmrenwu

    但事实上对 @zengshao @zmrenwu Match 对象的 group(1) 为 None ?这是怎么回事?

    songkaiape
        1
    songkaiape  
       Nov 28, 2016
    不知道你为什么这么写。。 re.sub(r'@(\w+)', mark, '@yangxg @zengshao @zmrenwu') 这样不就可以了么。后面输出为 None 的原因是因为你三个之间是 3 选 1 吧,匹配其中一个就不会匹配后面的了。
    你可以看看下面这篇文章
    http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html
    hanbaobao2005
        2
    hanbaobao2005  
       Nov 28, 2016
    如果这样呢?
    for i in ['@yangxg', '@zengshao', '@zmrenwu']:
    re.sub(r'@(yangxg|zengshao|zmrenwu)', mark, i)

    Python 会为每个() 分配 group, 你那种写法应该要判断 group(1), group(2), group(3)
    zmrenwu
        3
    zmrenwu  
    OP
       Nov 28, 2016
    @hanbaobao2005 谢谢,我错误理解了捕获组的含义,更正成这样就可以了: re.sub(r'@(yangxg|zengshao|zmrenwu)', mark, '@yangxg @zengshao @zmrenwu')
    zmrenwu
        4
    zmrenwu  
    OP
       Nov 28, 2016
    @songkaiape 嗯,你的是对的,只是因为我需要匹配特定的用户名,所以我把 (\w+) 改成了 (yangxg|zengshao|zmrenwu)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5259 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 07:40 · PVG 15:40 · LAX 00:40 · JFK 03:40
    ♥ Do have faith in what you're doing.