推荐学习书目
› 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
jander
V2EX  ›  Python

嵌套的正则表达式,求解

  •  
  •   jander · Jul 15, 2013 · 5218 views
    This topic created in 4823 days ago, the information mentioned may be changed or developed.
    有一个形如:'(1+(2+3)+4)+5'的字符串,
    正则表达式:r'\([^\)]+\)',只能匹配'(1+(2+3)',
    如何解决嵌套问题,匹配'(1+(2+3)+4)'。
    10 replies  •  1970-01-01 08:00:00 +08:00
    xunyu
        1
    xunyu  
       Jul 15, 2013
    用递归函数?
    jander
        2
    jander  
    OP
       Jul 15, 2013
    <http://twiki.org/cgi-bin/view/Blog/BlogEntry201109x3>提出了一种解决办法,不过是用Perl描述的,看不懂。
    大致思路是:
    1. 将字符串形式化,标注每个括号的层次。(这一步,没看懂原文怎么操作)
    '(1+(2+3)+4)+5'
    形式化后:
    '$LEVEL1(1+$LEVEL2(+3$LEVEL2)+4$LEVEL1)+5

    2. 然后就简单了,
    r'LEVEL1\([\s\S]+LEVEL1\)' 就可以匹配 '(1+(2+3)+4)'。
    caoyue
        3
    caoyue  
       Jul 15, 2013
    需要递归匹配和分组
    \([^\\(\)]*(((?'k'\()[^\\(\)]*)+((?'-k'\))[^\\(\)]*)+)*(?(k)(?!))\)
    之前的代码里面也用过

    不要问我怎么弄出来的,我忘了……
    picasso250
        4
    picasso250  
       Jul 15, 2013
    jander
        5
    jander  
    OP
       Jul 15, 2013
    @picasso250 Python不支持:平衡组/递归匹配
    caoyue
        6
    caoyue  
       Jul 15, 2013
    @jander 没注意节点……
    可以试试 pyparsing
    http://pyparsing.wikispaces.com/
    jander
        7
    jander  
    OP
       Jul 15, 2013
    解决了形式化的问题:

    http://gist.github.com/anonymous/5997860
    picasso250
        8
    picasso250  
       Jul 15, 2013
    @jander PCRE支持 (?R) ,python支持吗?

    说句实在话,如果真是这么简单的需求,自己写,比正则简单。

    extract string using /\(.+\)/
    for each character in string {
    if( come across '(' ) level++
    if( comeacross ')' ) level--
    if( level == 0 ) print string
    if( string come to end ) exit }
    rrfeng
        9
    rrfeng  
       Jul 15, 2013
    复杂的正则其实会降低程序的运行速度……
    不如切分自己处理

    或者你真的需要的是嵌套么?具体问题具体分析,可能根本不用嵌套
    Golevka
        10
    Golevka  
       Jul 15, 2013
    手撸一个top-down parser吧, 能直接构造出AST哦亲.

    expr : atom (+ atom)*
    atom : digit | '(' expr ')'
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2809 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 14:40 · PVG 22:40 · LAX 07:40 · JFK 10:40
    ♥ Do have faith in what you're doing.