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

python 正则匹配内容求助

  •  
  •   luyg · 2016-02-26 07:32:23 +08:00 · 2528 次点击
    这是一个创建于 2986 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

    python3.4 下测试通过
    thinkmore
        5
    thinkmore  
       2016-02-26 10:11:47 +08:00
    @luyg 匹配的内容不包括礼拜和理财
    lxy
        6
    lxy  
       2016-02-26 10:14:54 +08:00
    print re.search('礼拜(.+?)理财', b, re.S).group(0)
    如果匹配之间的字符就 group(1)
    wentian
        7
    wentian  
       2016-02-26 10:17:49 +08:00
    regex = re.compile(ur'(?!礼拜).+(?=理财)'), re.UNICODE | re.DOTALL | re.MULTILINE)
    popok
        8
    popok  
       2016-02-26 10:21:23 +08:00
    @lonelinsky 对的,回完贴就发现了,哈哈
    wentian
        9
    wentian  
       2016-02-26 10:23:46 +08:00
    (?<=礼拜).+(?=理财)
    上面用错了环视功能,楼主试试这个, 我已经测试通过了
    :)
    luyg
        10
    luyg  
    OP
       2016-02-26 12:46:48 +08:00
    @v2014 测试通过谢谢。
    luyg
        11
    luyg  
    OP
       2016-02-26 12:47:37 +08:00
    在这统一感谢,谢谢大家的帮助。问题圆满解决。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   880 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 19:31 · PVG 03:31 · LAX 12:31 · JFK 15:31
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.