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

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

  •  
  •   joyc · 2018-11-20 16:07:55 +08:00 · 2124 次点击
    这是一个创建于 1983 天前的主题,其中的信息可能已经有所发展或是发生改变。

    官方手册中如下:

    >>> 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 条回复    2018-11-21 08:54:24 +08:00
    ODD10
        1
    ODD10  
       2018-11-20 16:10:30 +08:00
    就是重复匹配的$1 内容????
    Ho
        2
    Ho  
       2018-11-20 16:12:37 +08:00
    这里是匹配第一个捕获组
    ODD10
        3
    ODD10  
       2018-11-20 16:13:07 +08:00
    al0ne
        4
    al0ne  
       2018-11-20 16:13:36 +08:00
    正则表达式反向引用 我理解的是\1 可以代表前面括号匹配到的内容
    ODD10
        5
    ODD10  
       2018-11-20 16:14:47 +08:00
    joyc
        6
    joyc  
    OP
       2018-11-20 16:15:39 +08:00
    @Ho
    @al0ne
    @ODD10
    正解啊,确实如此,匹配第一个捕获组,谢谢。
    katsusan
        7
    katsusan  
       2018-11-20 16:17:01 +08:00
    \1 应该是引用第一个分组(\b[a-z]+)
    jdhao
        8
    jdhao  
       2018-11-20 16:20:47 +08:00   ❤️ 1
    这个再 regex 里面叫 capture group,更多细节 Google "capture group regex"
    flowfire
        9
    flowfire  
       2018-11-21 08:54:24 +08:00 via iPhone
    就是$1,只不过一个是放在正则表达式里,一个是放在后面的替换字符里
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   979 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 21:18 · PVG 05:18 · LAX 14:18 · JFK 17:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.