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

关于 Python re 正则的一个请教

  •  
  •   siriussilen · 2019-09-04 20:58:13 +08:00 · 1683 次点击
    这是一个创建于 1696 天前的主题,其中的信息可能已经有所发展或是发生改变。

    打扰了,我现在憋在一个正则上面已经好久啦…

    https://www.douban.com/people/50583134/

    我想用正则提取出 people 后面的,50583134

    我在这里卡住了,网上也没有相关的材料。请大家不吝赐教 谢谢!

    10 条回复    2019-09-06 10:58:36 +08:00
    GTX765
        1
    GTX765  
       2019-09-04 21:10:44 +08:00 via iPhone   ❤️ 1
    re.find(r ‘ people/(.*?)/‘, string)试试 (妈的 iPhone 自带输入法的标点真操蛋)
    siriussilen
        2
    siriussilen  
    OP
       2019-09-04 21:14:25 +08:00
    @GTX765 感谢!!!!
    Dustyposa
        3
    Dustyposa  
       2019-09-04 21:19:14 +08:00   ❤️ 1
    re.search("\d+").group()
    delectate
        4
    delectate  
       2019-09-05 07:44:40 +08:00
    C:\Users\Delectate>python
    Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import re
    >>> str="https://www.douban.com/people/50583134/"
    >>> re.findall("\d+", str)
    ['50583134']
    >>>
    imlinhanchao
        5
    imlinhanchao  
       2019-09-05 09:05:06 +08:00
    完全可以不用正則吧,鏈接的格式是固定的,就直接用切片就行了:url[-9:-1]
    locoz
        6
    locoz  
       2019-09-05 11:22:11 +08:00
    这种很规则的东西,直接 split 会更方便,比如:
    >>> a = "https://www.douban.com/people/50583134/"
    >>> a.split("/")
    ['https:', '', 'www.douban.com', 'people', '50583134', '']
    >>> a.split("/")[4]
    '50583134'
    octalempyrean
        7
    octalempyrean  
       2019-09-05 11:32:05 +08:00 via Android   ❤️ 1
    你就爬吧
    xiaohanxxx
        8
    xiaohanxxx  
       2019-09-05 15:57:39 +08:00
    ''.join(re.findall(r'\d+',string))
    jxie0755
        9
    jxie0755  
       2019-09-06 01:42:20 +08:00
    这个格式如此的固定, 我觉得好像连正则都可以不用. 用字符串的方法就应该能解决.
    第一个回答 re.find(r ‘ people/(.*?)/‘, string) 就可以, 但是我会把(.*?)换成(\d*?)这样更精确?
    ClericPy
        10
    ClericPy  
       2019-09-06 10:58:36 +08:00
    "https?://www\.douban\.com/people/(\d+)/.*"
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1015 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 19:41 · PVG 03:41 · LAX 12:41 · JFK 15:41
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.