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

python 正则匹配内容求助

  •  
  •   luyg · Feb 26, 2016 · 3596 views
    This topic created in 3866 days ago, the information mentioned may be changed or developed.

    各位大神,我有一段话是这样的,想匹配从礼拜开始到理财之间的内容,我写的正则匹配不出来,求大神帮忙。

    b= 'hello this is book . \n \
    test . \n \
    abc 礼拜 test \n \
    doing what ? \n \
    abc 理财 ddd \n \
    this is the end '
    print b
    print re.search(u'礼拜(.*?)理财',b)
    这里输出是 None ,但是如果不加后面的理财,就可以匹配上。

    11 replies  •  2016-02-26 12:47:37 +08:00
    v2014
        1
    v2014  
       Feb 26, 2016
    re.search(u'礼拜(.*?)理财',b, re.DOTALL))
    https://docs.python.org/3/library/re.html#re.DOTALL
    默认.不包括换行,加了 DOTALL 标志才是所有字符
    popok
        2
    popok  
       Feb 26, 2016
    @v2014 礼拜([^理财]*)理财
    换行也包括了,哈哈
    lonelinsky
        3
    lonelinsky  
       Feb 26, 2016
    @popok 但是你这样的写法,如果中间出现单独的理字或财字就会出问题了…
    thinkmore
        4
    thinkmore  
       Feb 26, 2016
    (?s)(?<=(礼拜)).*(?=理财)

    python3.4 下测试通过
    thinkmore
        5
    thinkmore  
       Feb 26, 2016
    @luyg 匹配的内容不包括礼拜和理财
    lxy
        6
    lxy  
       Feb 26, 2016
    print re.search('礼拜(.+?)理财', b, re.S).group(0)
    如果匹配之间的字符就 group(1)
    wentian
        7
    wentian  
       Feb 26, 2016
    regex = re.compile(ur'(?!礼拜).+(?=理财)'), re.UNICODE | re.DOTALL | re.MULTILINE)
    popok
        8
    popok  
       Feb 26, 2016
    @lonelinsky 对的,回完贴就发现了,哈哈
    wentian
        9
    wentian  
       Feb 26, 2016
    (?<=礼拜).+(?=理财)
    上面用错了环视功能,楼主试试这个, 我已经测试通过了
    :)
    luyg
        10
    luyg  
    OP
       Feb 26, 2016
    @v2014 测试通过谢谢。
    luyg
        11
    luyg  
    OP
       Feb 26, 2016
    在这统一感谢,谢谢大家的帮助。问题圆满解决。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2600 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 05:40 · PVG 13:40 · LAX 22:40 · JFK 01:40
    ♥ Do have faith in what you're doing.