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

问个正则

  •  
  •   imn1 · 2018-07-13 12:23:37 +08:00 · 1747 次点击
    这是一个创建于 2086 天前的主题,其中的信息可能已经有所发展或是发生改变。
    string "[123]...(abc)"
    需要将“ 123 ”提取到 key1,"abc"提取到 key2,(?<key1>)方式

    问题是
    [] 和 () 出现的顺序不确定,也可能是
    string "(abc)...[123]"

    能否一条正则搞定?
    第 1 条附言  ·  2018-07-13 13:18:31 +08:00
    脑子秀逗了,忘了 findall 一个很重要的设定:
    findall 的输出是按 pattern 中分组的顺序,而不是 string 中匹配出现的顺序

    m=re.findall(r"(\{([a-z]+)\})|(\[([0-9]+)\])|(\(([a-z]+)\))", "(ace).[92387492].{abc}")

    m
    Out[24]:
    [('', '', '', '', '(ace)', 'ace'),
    ('', '', '[92387492]', '92387492', '', ''),
    ('{abc}', 'abc', '', '', '', '')]

    按照结果每个 tuple 的 index 读取就可以了
    7 条回复    2018-07-17 12:46:33 +08:00
    wizardoz
        1
    wizardoz  
       2018-07-13 12:54:26 +08:00   ❤️ 1
    "\[(?P<key1>[0-9]+)\].+\((?P<key2>[a-z]+)\)"
    imn1
        2
    imn1  
    OP
       2018-07-13 12:59:57 +08:00
    @wizardoz
    你应该没看完问题
    zynlp
        3
    zynlp  
       2018-07-13 13:16:40 +08:00 via iPhone   ❤️ 1
    会不会有嵌套的情况呢?
    rocketman13
        4
    rocketman13  
       2018-07-15 15:36:00 +08:00
    正则我要提取或者替换的的文本中既有双引号也有单引号,那我概括选中这段文本时是不是要用三引号??
    imn1
        5
    imn1  
    OP
       2018-07-15 15:43:31 +08:00
    @rocketman13
    你干吗不自己发个帖问啊?

    不需要,用转义就可以了,\' or \" 视乎外面用哪个
    rocketman13
        6
    rocketman13  
       2018-07-15 22:25:03 +08:00
    @imn1 可以的
    frostming
        7
    frostming  
       2018-07-17 12:46:33 +08:00
    (?=.*?(\[.+?\]))(?=.*?(\(.+?\))).+?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4093 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 05:22 · PVG 13:22 · LAX 22:22 · JFK 01:22
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.