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

Python 正则问题

  •  
  •   lemonnn · 2021-01-01 09:37:29 +08:00 · 2025 次点击
    这是一个创建于 1220 天前的主题,其中的信息可能已经有所发展或是发生改变。
    我想要匹配"[ )"或者 "( ]"中的内容,于是我写了这样一个正则:
    str = '[123)(abc]'
    m = re.findall('\[(.*?)\)|\((.*?)]',str)

    我想要得到[’123‘ , ’abc‘]这样一个数组结果
    但结果是[('123', ' '), (' ', 'abc')]
    8 条回复    2021-01-01 15:15:51 +08:00
    ClericPy
        1
    ClericPy  
       2021-01-01 09:56:59 +08:00
    import re

    string = '[123)(abc]'

    m = re.findall(r'[\[()](.*?)[)\]]', string)
    print(m)
    # ['123', 'abc']

    这样吗?
    ClericPy
        2
    ClericPy  
       2021-01-01 09:57:25 +08:00
    上面发错, 被自动补全了括号

    # -*- coding: utf-8 -*-

    import re

    string = '[123)(abc]'

    m = re.findall(r'[\[(](.*?)[)\]]', string)
    print(m)
    ClericPy
        3
    ClericPy  
       2021-01-01 09:58:23 +08:00
    睡晕了... 上面这俩回复都不对... 会有误判
    crclz
        4
    crclz  
       2021-01-01 10:00:50 +08:00
    ('123', '') 表示 123 在第一个 group(括号)内被匹配。
    ('', 'abc') 表示 abc 在第二个 group(括号)内被匹配。
    crclz
        5
    crclz  
       2021-01-01 10:03:32 +08:00
    import re

    def single(l):
    assert len(l) == 1
    return l[0]

    s = '[123)(abc]'

    # m = re.findall()
    m = re.findall('\[(.*?)\)|\((.*?)]',s)
    m = [single([q for q in p if len(q)>0]) for p in m]
    print(m)
    ClericPy
        6
    ClericPy  
       2021-01-01 10:16:30 +08:00
    # -*- coding: utf-8 -*-

    import re

    string = '[123)(abc]'

    m = re.findall(r'(?<=\[).*?(?=\))|(?<=\().*?(?=\])', string)
    print(m)
    # ['123', 'abc']
    lemonnn
        7
    lemonnn  
    OP
       2021-01-01 10:27:31 +08:00
    解决了,谢谢。 @ClericPy @crclz
    learningman
        8
    learningman  
       2021-01-01 15:15:51 +08:00
    @ClericPy 在这种回复不支持 markdown 的网站发代码,可以用 pastebin
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2717 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 14:55 · PVG 22:55 · LAX 07:55 · JFK 10:55
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.