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

Python 菜鸟求助正则(?:...)

  •  
  •   mikefy · 2018-05-31 18:57:09 +08:00 · 2342 次点击
    这是一个创建于 2128 天前的主题,其中的信息可能已经有所发展或是发生改变。

    在 python 核心编程中看到这样一个例子: ''' print re.findall('http://(?:\w+.)(\w+.com)', 'http://code.google.com') ''' 最后的结果是输出['google.com']. 请问为什么前面的 http://没有掉了,求助...

    12 条回复    2018-05-31 19:38:01 +08:00
    liuxu
        1
    liuxu  
       2018-05-31 19:00:04 +08:00   ❤️ 2
    正则的()是捕获匹配,会返回的,其他的不会返回给你
    malaohu
        2
    malaohu  
       2018-05-31 19:03:34 +08:00
    建议楼主 查询一下 ?: 的意思
    summerwar
        3
    summerwar  
       2018-05-31 19:03:50 +08:00
    因为没有在括号里
    summerwar
        4
    summerwar  
       2018-05-31 19:08:50 +08:00
    (?:pattern)

    匹配 pattern,但不捕获匹配结果。

    顺手学了个新东西,感谢
    mikefy
        5
    mikefy  
    OP
       2018-05-31 19:12:05 +08:00
    原来这就是子组...另外这里有写错没有给.加上反斜杠没人看见吗...嘎嘎
    F1024
        6
    F1024  
       2018-05-31 19:17:59 +08:00
    ()= 分组匹配 = 捕获组

    即只会返回括号内的内容

    (?:)只匹配不显示

    (?:\w+.) 这句匹配到了" code. "只匹配不显示
    (\w+.com)' 这句匹配 google.com 并显示出来
    hahastudio
        7
    hahastudio  
       2018-05-31 19:20:04 +08:00
    1. help('re.findall') Return a list of all non-overlapping matches in the string
    2. https://deerchao.net/tutorials/regex/regex.htm 匹配 exp,不捕获匹配的文本,也不给此分组分配组号
    hahastudio
        8
    hahastudio  
       2018-05-31 19:21:08 +08:00
    @mikefy 反正 . 也匹配 .
    0x400
        9
    0x400  
       2018-05-31 19:22:47 +08:00 via Android
    所以要怎么才能返回全部呢。比如我想要以 a 或者 b 开头加后面五个任意字符(a|b).{5}这样肯定不行,只能(a.{5}|b.{5}),但是。。。如果有 abcdefg 等等很多情况开头呢,又或者后面相同的条件也很长。。。
    liuxu
        10
    liuxu  
       2018-05-31 19:26:34 +08:00
    @0x400
    ([a-z].{5})
    xml123
        11
    xml123  
       2018-05-31 19:37:08 +08:00
    @0x400 把你想返回的部分加个括号就行了,返回整个匹配就加到最外面,另外表达式里没出现括号好像也是返回整个匹配。
    F1024
        12
    F1024  
       2018-05-31 19:38:01 +08:00
    @0x400

    import re
    print(re.findall('\w+\d+', 'abcdefg12345')) 这样岂不美哉
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3566 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 04:47 · PVG 12:47 · LAX 21:47 · JFK 00:47
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.