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

请问行家,正则中的“\1”怎么正确的理解

  •  
  •   joyc · Nov 20, 2018 · 2632 views
    This topic created in 2733 days ago, the information mentioned may be changed or developed.

    官方手册中如下:

    >>> import re
    >>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
    ['foot', 'fell', 'fastest']
    >>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
    'cat in the hat'
    

    我知道第一个中的\b是单词边界,那么第二个中的\1 具体是什么意思,向后重复匹配的意思吗?

    9 replies    2018-11-21 08:54:24 +08:00
    uTOmOuk3L6sb4MSI
        1
    uTOmOuk3L6sb4MSI  
       Nov 20, 2018
    就是重复匹配的$1 内容????
    Ho
        2
    Ho  
       Nov 20, 2018
    这里是匹配第一个捕获组
    uTOmOuk3L6sb4MSI
        3
    uTOmOuk3L6sb4MSI  
       Nov 20, 2018
    al0ne
        4
    al0ne  
       Nov 20, 2018
    正则表达式反向引用 我理解的是\1 可以代表前面括号匹配到的内容
    uTOmOuk3L6sb4MSI
        5
    uTOmOuk3L6sb4MSI  
       Nov 20, 2018
    joyc
        6
    joyc  
    OP
       Nov 20, 2018
    @Ho
    @al0ne
    @ODD10
    正解啊,确实如此,匹配第一个捕获组,谢谢。
    katsusan
        7
    katsusan  
       Nov 20, 2018
    \1 应该是引用第一个分组(\b[a-z]+)
    jdhao
        8
    jdhao  
       Nov 20, 2018   ❤️ 1
    这个再 regex 里面叫 capture group,更多细节 Google "capture group regex"
    flowfire
        9
    flowfire  
       Nov 21, 2018 via iPhone
    就是$1,只不过一个是放在正则表达式里,一个是放在后面的替换字符里
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   897 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 96ms · UTC 20:30 · PVG 04:30 · LAX 13:30 · JFK 16:30
    ♥ Do have faith in what you're doing.