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

正则表达式 (?<=exp) 消耗字符吗?

  •  
  •   explist · 2016-11-15 17:03:27 +08:00 · 2545 次点击
    这是一个创建于 2717 天前的主题,其中的信息可能已经有所发展或是发生改变。
    http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html
    这个网址上说不消耗字符,但,实验了下,好像并不如此:

    import re
    a='set 2ddp'
    b=re.search(r'(?=set).*',a)
    print(b.group(0)) # 此处完整输出 a 这个是真正的不消耗字符
    b=re.search(r'(?<=set).*',a)
    print(b.group(0)) # 此处输出:' 2ddp'
    8 条回复    2016-11-15 19:10:02 +08:00
    explist
        1
    explist  
    OP
       2016-11-15 17:06:51 +08:00
    JavaScript 好像不支持,无法可视化
    philions
        2
    philions  
       2016-11-15 17:26:55 +08:00   ❤️ 1
    look around 匹配的是位置,(?<=set)正好匹配在 set 后的空格开始位置
    fy
        3
    fy  
       2016-11-15 17:28:43 +08:00   ❤️ 1
    不消耗,所有特殊组都不消耗字符串。

    拙作: https://github.com/fy0/tinyre
    littleshy
        4
    littleshy  
       2016-11-15 17:29:54 +08:00   ❤️ 1
    (?=set) 是从 set 之前开始匹配;
    (?<=set) 是从 set 后面开始匹配。
    DiamondbacK
        5
    DiamondbacK  
       2016-11-15 17:34:55 +08:00   ❤️ 1
    look around 属于零宽断言,不消耗字符。
    JavaScript 只支持 look ahead ,不支持 look behind 。
    explist
        6
    explist  
    OP
       2016-11-15 17:41:14 +08:00
    这样理解:
    所说的之前之后,都有一个定点,即当前位置。在当前位置前后预查满足要求后,就在这个定点处开始真正的匹配
    vugusurk
        7
    vugusurk  
       2016-11-15 18:05:55 +08:00   ❤️ 1
    这是 lookbehind ,基于当前位置;所以不存在消耗字符与否这个说法,根本就没有字符可以“消耗”。
    iyangyuan
        8
    iyangyuan  
       2016-11-15 19:10:02 +08:00 via iPhone
    只是预测而已,不会匹配到
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3340 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 11:38 · PVG 19:38 · LAX 04:38 · JFK 07:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.