推荐学习书目
› 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 · 3714 views
    This topic created in 3906 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
    v2014
    Feb 26, 2016
    1
    re.search(u'礼拜(.*?)理财',b, re.DOTALL))
    https://docs.python.org/3/library/re.html#re.DOTALL
    默认.不包括换行,加了 DOTALL 标志才是所有字符
    popok
    popok
    Feb 26, 2016
    2
    @v2014 礼拜([^理财]*)理财
    换行也包括了,哈哈
    lonelinsky
    lonelinsky
    Feb 26, 2016
    3
    @popok 但是你这样的写法,如果中间出现单独的理字或财字就会出问题了…
    thinkmore
    thinkmore
    Feb 26, 2016
    4
    (?s)(?<=(礼拜)).*(?=理财)

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