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

求助: Python 正则模块 search findall 表现不同

  •  
  •   Leon6868 · 195 天前 · 1045 次点击
    这是一个创建于 195 天前的主题,其中的信息可能已经有所发展或是发生改变。

    正则表达式如下

    ( https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]
    

    复现代码:

    import re
    url_pattern = re.compile(r'( https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]')
    print("search", url_pattern.search("http://1.com 和 http://2.com"))
    print("findall", url_pattern.findall("http://1.com 和 http://2.com"))
    

    为什么二者表现不同呢?如果我想用 url_pattern.findall() 得到 ["http://1.com","http://2.com"] 这样的结果,该如何修改代码?

    第 1 条附言  ·  195 天前

    感谢 @hicdn #2 的回答,将表达式修改为 (?:https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|] 即可正常匹配 URL

    4 条回复    2023-10-20 00:29:14 +08:00
    J0rmo
        1
    J0rmo  
       195 天前
    import re

    url_pattern = re.compile(r'( https?|ftp|file)(://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|])')

    print([ ''.join(v) for v in url_pattern.findall("http://1.comhttp://2.com") ])
    hicdn
        2
    hicdn  
       195 天前   ❤️ 1
    你用了正则的分组,() 内的内容就是分组,findall 在有分组时,只返回分组匹配内容。
    不分组就能得到你期望的结果
    ( https?|ftp|file)
    ->
    (?: https?|ftp|file)
    guog
        3
    guog  
       195 天前
    import re

    # 如果没啥特殊匹配要求的话可以简化正则

    url_pattern = r'( https?|ftp|file)://\S+'

    text = "http://1.comhttp://2.com"

    matches = re.finditer(url_pattern, text)

    results = []

    if matches:
    results = [match.group() for match in matches]
    print(results)
    else:
    print("No URLs found.")
    Leon6868
        4
    Leon6868  
    OP
       195 天前
    @hicdn #2 感谢!我在 js 下使用这个正则就没有问题,请问是 findall 的特性吗?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2254 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 03:47 · PVG 11:47 · LAX 20:47 · JFK 23:47
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.