推荐学习书目
› 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 · 3042 views
    This topic created in 2913 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
    uTOmOuk3L6sb4MSI
    Nov 20, 2018
    1
    就是重复匹配的$1 内容????
    Ho
    Ho
    Nov 20, 2018
    2
    这里是匹配第一个捕获组
    al0ne
    al0ne
    Nov 20, 2018
    4
    正则表达式反向引用 我理解的是\1 可以代表前面括号匹配到的内容
    joyc
    joyc
    OP
    Nov 20, 2018
    6
    @Ho
    @al0ne
    @ODD10
    正解啊,确实如此,匹配第一个捕获组,谢谢。
    katsusan
    katsusan
    Nov 20, 2018
    7
    \1 应该是引用第一个分组(\b[a-z]+)
    jdhao
    jdhao
    Nov 20, 2018❤️1
    8
    这个再 regex 里面叫 capture group,更多细节 Google "capture group regex"
    flowfire
    flowfire
    Nov 21, 2018 via iPhone
    9
    就是$1,只不过一个是放在正则表达式里,一个是放在后面的替换字符里
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2092 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 15:08 · PVG 23:08 · LAX 07:08 · JFK 10:08
    ♥ Do have faith in what you're doing.