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

嵌套的正则表达式,求解

  •  
  •   jander · 2013-07-15 10:27:51 +08:00 · 3879 次点击
    这是一个创建于 3938 天前的主题,其中的信息可能已经有所发展或是发生改变。
    有一个形如:'(1+(2+3)+4)+5'的字符串,
    正则表达式:r'\([^\)]+\)',只能匹配'(1+(2+3)',
    如何解决嵌套问题,匹配'(1+(2+3)+4)'。
    10 条回复    1970-01-01 08:00:00 +08:00
    xunyu
        1
    xunyu  
       2013-07-15 10:34:31 +08:00
    用递归函数?
    jander
        2
    jander  
    OP
       2013-07-15 11:12:06 +08:00
    <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  
       2013-07-15 11:50:40 +08:00
    需要递归匹配和分组
    \([^\\(\)]*(((?'k'\()[^\\(\)]*)+((?'-k'\))[^\\(\)]*)+)*(?(k)(?!))\)
    之前的代码里面也用过

    不要问我怎么弄出来的,我忘了……
    picasso250
        4
    picasso250  
       2013-07-15 12:47:04 +08:00
    jander
        5
    jander  
    OP
       2013-07-15 12:58:47 +08:00
    @picasso250 Python不支持:平衡组/递归匹配
    caoyue
        6
    caoyue  
       2013-07-15 13:19:11 +08:00
    @jander 没注意节点……
    可以试试 pyparsing
    http://pyparsing.wikispaces.com/
    jander
        7
    jander  
    OP
       2013-07-15 14:29:41 +08:00
    解决了形式化的问题:

    http://gist.github.com/anonymous/5997860
    picasso250
        8
    picasso250  
       2013-07-15 16:38:58 +08:00
    @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  
       2013-07-15 16:42:32 +08:00
    复杂的正则其实会降低程序的运行速度……
    不如切分自己处理

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

    expr : atom (+ atom)*
    atom : digit | '(' expr ')'
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1089 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 18:52 · PVG 02:52 · LAX 11:52 · JFK 14:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.